自定义DialogFragment如何与打开它…
来源:互联网 发布:jdk 7u55 linux x64 编辑:程序博客网 时间:2024/05/21 10:32
andoid自定义Fragment继承DialogFragment,实现自定义的dialog界面后,如何与打开它的activity或Fragment进行事件的传递?
在自定义的Fragment里定义一个接口,接口里的方法为响应点击事件而定义
public class NoticeDialogFragment extends DialogFragment {
publicinterface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
// Use thisinstance of the interface to deliver action events
NoticeDialogListener mListener;
// Overridethe Fragment.onAttach() method to instantiate theNoticeDialogListener
@Override
public voidonAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callbackinterface
try {
// Instantiate the NoticeDialogListener so we can send events tothe host
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throwexception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
@Override
publicDialog onCreateDialog(Bundle savedInstanceState) {
// Build the dialog and set up the button click handlers
AlertDialog.Builder builder = newAlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, newDialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the positive button event back to the host activity