DialogFragment的用法实例

    DialogFragment,顾名思义,是一个显示dialog窗口的fragment。外表和对话框没什么区别,我们一般在android4.0以后建议用DialogFragment来替代AlertDialog。DialogFragment比AlertDialog有很多优点,比如说,它是独立的,有自己的window,接受自己的输入事件。

 

public static class MyAlertDialogFragment extends DialogFragment{

    	public static MyAlertDialogFragment newInstance(int id){
    		MyAlertDialogFragment dialogFragment = new MyAlertDialogFragment();
    		Bundle bundle = new Bundle();
    		bundle.putInt("dialogId", id);
    		dialogFragment.setArguments(bundle);
    		return dialogFragment;
    	}
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			int id =getArguments().getInt("dialogId");
			switch (id) {
	        case DIALOG_YES_NO_MESSAGE:
	            return new AlertDialog.Builder(getActivity())
	                .setIconAttribute(android.R.attr.alertDialogIcon)
	                .setTitle(R.string.alert_dialog_two_buttons_title)
	                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {

	                        /* User clicked OK so do some stuff */
	                    }
	                })
	                .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {

	                        /* User clicked Cancel so do some stuff */
	                    }
	                })
	                .create();


一般建立一个静态类,继承父类DialogFragment,里面写一个newInstance方法,去实例一个对象,可以重写onCreateDialog或者oncreateview.在acitivity中调用show方法就可以显示出来,非常简单。

 

Button twoButtonsTitle = (Button) findViewById(R.id.two_buttons);
        twoButtonsTitle.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                MyAlertDialogFragment alertDialogFragment = MyAlertDialogFragment.newInstance(DIALOG_YES_NO_MESSAGE);
                alertDialogFragment.show(getFragmentManager(), null);
            }
        });


 

附上源代码

   

你可能感兴趣的:(android)