10

我想将一个片段添加到对话框(可以是DialogFragment或常规对话框)。我怎么做?将片段添加到对话框

这里是我的DialogFragment:

public class MyDialogFragment extends DialogFragment { 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     MyDialogFragment2 dialog = new MyDialogFragment2(); 
     View v = inflater.inflate(R.layout.news_articles, container, false); 
     getActivity().getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, dialog).commit(); 
     return v; 
    } 

} 

这里的news_article.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/fragment_container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

这是我的主要活动:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
      MyDialogFragment dialog = new MyDialogFragment(); 
      dialog.show(getSupportFragmentManager(), "asdf"); 
     } 
    }); 
} 

但是当我尝试它,我得到:

No view found for id 0x7f070002 for fragment MyDialogFragment2 

我认为这是因为活动的FragmentManager不是我应该添加到的那个,但我找不到DialogFragment的一个,它在哪里? 。

+2

'getChildFragmentManager()。beginTransaction()....' – Luksprog

+0

谢谢,但是这只适用于API 17,不是吗? – Kalisky

+1

从4.2开始引入原生片段。但是您始终可以选择支持兼容性包中的片段,该包使用相同的'getChildFragmentManager()'方法。 – Luksprog

回答

7

的对话框布局 - R.layout.view_with_plus

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/container" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.util.me.TestActivity" 
    > 

    <TextView 
     android:id="@+id/text" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Details"/> 
    <fragment 
     android:layout_toRightOf="@+id/text" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/email" 
     class="com.util.me.test.PlusOneFragment" 
     android:layout_centerHorizontal="true"/> 

</RelativeLayout> 

如何显示对话框

public void showDialog(View vIew){ 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 

    View view = this.getLayoutInflater().inflate(R.layout.view_with_plus, null); 
    builder.setView(view) 
      .setPositiveButton("OK", null) 
      .setNegativeButton("Cancel", null); 

    AlertDialog dialog = builder.create(); 
    dialog.show(); 
} 

class =“com.util.me.test.PlusOneFragment”中的片段只是Android Studio生成的PlusOneFragment。