通过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中的一个。如果重写两个,将会抛出异常。

你可能感兴趣的:(通过Dialog Fragment管理和显示对话框)