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);
            }
        });


 

附上源代码

   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值