设为首页 加入收藏

TOP

通过Dialog Fragment管理和显示对话框
2015-07-20 18:00:26 来源: 作者: 【 】 浏览:1
Tags:通过 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中的一个。如果重写两个,将会抛出异常。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇(objc/runtime.h)中Associative机.. 下一篇HDU 4910 Problem about GCD(米勒..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: