通过Dialog Fragment管理和显示对话框

要想使用Dialog Fragment,可以扩展DialogFragment类,重写onCreateDialog处理程序。

package com.example.androidtest;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;

@SuppressLint("NewApi")
public class MyDialogFragment extends DialogFragment{
	private static String CURRENT_TIME = "CURRENT_TIME";
	
	public static MyDialogFragment newInstance(String currentTime){
		//创建一个新的带有参数的Fragment实例
		MyDialogFragment fragment = new MyDialogFragment();
		Bundle args = new Bundle();
		args.putString(CURRENT_TIME, currentTime);
		fragment.setArguments(args);
		return fragment;
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		//使用AlertBuilder创建新的对话框
		AlertDialog.Builder timeDialog = new AlertDialog.Builder(getActivity());
		//配置对话框UI
		timeDialog.setTitle("The current time is ...");
		timeDialog.setMessage(getArguments().getString(CURRENT_TIME));
		return timeDialog.create();
	}
	

}

如何调用:

String tag = "my_dialog";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		DialogFragment myFragment = MyDialogFragment.newInstance(df.format(new Date()));
		myFragment.show(getFragmentManager(), tag);

另外,可以通过重写onCreateView处理程序来在Dialog Fragment中填充一个自定义的对话框布局,就像在自定义Dialog类中所使用的一样:

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// 填充对话框的UI
		View view = inflater.inflate(R.layout.dialog_view, container,false);
		return view;
	}

注意,只能重写onCreateView和onCreateDialog中的一个。如果重写两个,将会抛出异常。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值