顾名思义,DialogFragment就是一个浮动在Activity上面的Fragment。当需要用户的反馈时,它就会派上用场。下面将会展示如何使用DialogFragment,与使用ListFragment类似,需要继承DialogFragment基类。
1、创建一个工程:DialogFragmentExample
2、在包路径下面新建一个类Fragment1
- public class Fragment1 extends DialogFragment {
- static Fragment1 newInstance(String title) {
- Fragment1 fragment = new Fragment1();
- Bundle args = new Bundle();
- args.putString("title", title);
- fragment.setArguments(args);
- return fragment;
- }
-
- @Override
- public Dialog onCreateDialog(Bundle savedInstanceState) {
- String title = getArguments().getString("title");
- return new AlertDialog.Builder(getActivity())
- .setIcon(R.drawable.ic_launcher)
- .setTitle(title)
- .setPositiveButton("OK",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog,
- int whichButton) {
- ((DialogFragmentExampleActivity)
- getActivity()).doPositiveClick();
- }
- })
- .setNegativeButton("Cancel",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog,
- int whichButton) {
- ((DialogFragmentExampleActivity)
- getActivity()).doNegativeClick();
- }
- }).create();
- }
- }
3、DialogFragmentExampleActivity.java中的代码
- public class DialogFragmentExampleActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- Fragment1 dialogFragment = Fragment1.newInstance(
- "Are you sure you want to do this?");
- dialogFragment.show(getFragmentManager(), "dialog");
- }
-
- public void doPositiveClick() {
- //---perform steps when user clicks on OK---
- Log.d("DialogFragmentExample", "User clicks on OK");
- }
-
- public void doNegativeClick() {
- //---perform steps when user clicks on Cancel---
- Log.d("DialogFragmentExample", "User clicks on Cancel");
- }
-
- }
4、按F11在模拟器上调试,会看到一个对话框,点击OK或Cancel按钮会弹出消息。
注:在Android 4.0版本以后,官方推荐使用DialogFragment去替换Dialog。大家可以看看Android 4.0的Launcher等源码,这些源码中大量使用了Fragment类。
阅读(11973) | 评论(0) | 转发(0) |