这是一个是/否DialogFragment的完整示例:
班上:
public class SomeDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setMessage("Sure you wanna do this!")
.setNegativeButton(android.R.string.no, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do nothing (will close dialog)
}
})
.setPositiveButton(android.R.string.yes, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do something
}
})
.create();
}
}
要启动对话框:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Create and show the dialog.
SomeDialog newFragment = new SomeDialog ();
newFragment.show(ft, "dialog");
您还可以让该类实现onClickListener并使用它代替嵌入式侦听器。
回呼活动
如果要实现回调,请按以下步骤操作:
YourActivity extends Activity implements OnFragmentClickListener
和
@Override
public void onFragmentClick(int action, Object object) {
switch(action) {
case SOME_ACTION:
//Do your action here
break;
}
}
回调类:
public interface OnFragmentClickListener {
public void onFragmentClick(int action, Object object);
}
然后要从片段执行回调,您需要确保已将侦听器连接如下:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement listeners!");
}
}
然后执行如下回调:
mListener.onFragmentClick(SOME_ACTION, null); // null or some important object as second parameter.