这是一个是/否 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.