alexanderblom指出DialogFragment
可以作为对话框,但是通过使用setShowsDialog(false);
可以让其充当Fragment。
最终以下内容对我有用:
文件:res/layout/wifidirect_dialog_wifidirect:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/dialog_wifidirect_layout">
<LinearLayout
android:id="@+id/frag_container"
android:layout_width="match_parent"
android:layout_height="250dp"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/frag_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top" >
</RelativeLayout>
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginBottom="0dp"
android:background="?android:attr/dividerVertical" />
<Button
android:id="@+id/dialog_wifidirect_cancel"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/cancel"/>
</LinearLayout>
文件 src/.../WifiDirectDialog.java:
public class WiFiDirectDialog extends DialogFragment {
public static final String TAG = "WifiDirectDialog";
public static final String DEVICE_LIST_FRAGMENT_TAG = "WIFIDIRECT_DEVICE_LIST_FRAGMENT";
public static WiFiDirectDialog newInstance(){
WiFiDirectDialog wDialog = new WiFiDirectDialog();
wDialog.setShowsDialog(false);
wDialog.setRetainInstance(true);
wDialog.setCancelable(false);
return wDialog;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v(TAG,"onCreateView");
View view = inflater.inflate(R.layout.wifidirect_dialog_wifidirect,container, false);
ListFragment listFragment = new YourListFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.addToBackStack(DEVICE_LIST_FRAGMENT_TAG)
.replace(R.id.frag_list,deviceListFragment,DEVICE_LIST_FRAGMENT_TAG)
.commit();
return view;
};
@Override
public void onActivityCreated(Bundle savedInstanceState){
Log.v(TAG,"onActivityCreated");
super.onActivityCreated(savedInstanceState);
Dialog dialog = getDialog();
dialog.setTitle(R.string.wifidirect_dialog_title);
Button cancelButton = (Button) view.findViewById(R.id.dialog_wifidirect_cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
}