如何使用DialogFragment类来创建和显示对话框

12年前
本示例演示如何使用DialogFragment类来显示和管理一个AlertDialog对话框。代码在Android3.0中编译测试通过。

1. 定义清单文件(AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

      package="my.android.test"

      android:versionCode="1"

      android:versionName="1.0">

    <uses-sdk android:minSdkVersion="11" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <!-- android:enabled

              这个属性用于指定Activity是否能够被安装到系统中,如果设置为true则能够安装,否则不能安装

              默认设置时true -->

        <activity android:name=".FragmentAlertDialog"

                  android:label="@string/app_name"

                  android:enabled="@bool/atLeastHoneycomb">

           <intent-filter>

               <action android:name="android.intent.action.MAIN" />

               <category android:name="android.intent.category.LAUNCHER" />

           </intent-filter>

        </activity>

    </application>

</manifest>

2. 定义资源文件(strings.xmlbools.xml

strings.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <string name="hello">Hello World, FragmentAlertDialog!</string>

    <string name="app_name">FragmentDialog</string>

    <string name="fragment_hide_show">Fragment/Hide and Show</string>

    <string name="fragment_context_menu">Fragment/Context Menu</string>

    <string name="fragment_context_menu_msg">Fragment populating a context

            menu; long press the button to see.</string>

    <string name="long_press">Long press me</string>

    <string name="fragment_dialog">App/Fragment/Dialog</string>

    <string name="show">Show</string>

    <string name="alert_dialog_two_buttons_title">

        Lorem ipsum dolor sit aie consectetur adipiscing\nPlloaso mako nuto

        siwuf cakso dodtos anr koop.

    </string>

    <string name="alert_dialog_cancel">Cancel</string>

    <string name="alert_dialog_ok">OK</string>

</resources>

bools.xml

<?xml version="1.0" encoding="utf-8"?>

<resources>

    <bool name="atLeastHoneycomb">true</bool>

</resources>

3. 定义布局文件(fragment_dialog.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical" android:padding="4dip"

    android:gravity="center_horizontal"

    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView

            android:id="@+id/text"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:layout_gravity="center_vertical|center_horizontal"

            android:textAppearance="?android:attr/textAppearanceMedium"

            android:gravity="top|center_horizontal" />

 

    <Button android:id="@+id/show"

        android:layout_width="wrap_content" android:layout_height="wrap_content"

        android:layout_weight="0"

        android:text="@string/show">

        <requestFocus />

    </Button>

</LinearLayout>

4. 创建Activity类文件(FragmentAlertDialog.java

package my.android.test;

 

import android.app.Activity;

import android.app.AlertDialog;

import android.app.Dialog;

import android.app.DialogFragment;

import android.content.DialogInterface;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

 

publicclass FragmentAlertDialogextends Activity {

    /** Activity被首次创建时,系统会调用这个方法 */

    @Override

    publicvoid onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        //把布局文件填充到Activity

        setContentView(R.layout.fragment_dialog);

        //查找布局中的text元素,并设置要显示的文本。

        View tv = findViewById(R.id.text);

        ((TextView)tv).setText("Example of displaying an alert dialog with a DialogFragment");

        //查找布局中的show按钮,并设置点击事件监听器。用户点击时该按钮时,显示一个Fragment对话框。

        Button button = (Button)findViewById(R.id.show);

        button.setOnClickListener(new OnClickListener(){

        publicvoid onClick(View v){

             showDialog();

        }

        });

    }

    /**

     * 显示Fragment对话框。

     */

    void showDialog(){

    //获取Fragment对话框实例,在获取实例的时候,设置这个对话框的标题。

    DialogFragment newFragment = MyAlertDialogFragment.newInstance(

            R.string.alert_dialog_two_buttons_title);

    /**

     * 显示Fragment对话框。

     * show(FragmentManager, String)方法:本方法把Fragment添加到给定的Fragment管理器中,并显示对话框。

     * 对于创建明确的事务、给Fragment对象添加给定的标签,并提交这个事务,这个方法是非常方便的。

     * 这个方法不会把事务添加到回退堆栈中。当这个Fragment被关闭时,要执行一个新的从Activity

     * 删除这个Fragment对象的事务。

     * FragmentManager:指定Fragment对象要被添加到Fragment管理器对象。

     * String:指定Fragment对象的标签。

     */

    newFragment.show(getFragmentManager(), "dialog");

    }

    /**

     * 定义Fragment对话框对象ok按钮点击时,要执行的方法。

     */

    publicvoid doPositiveClick(){

    Log.i("FragmentAlertDialog","Positive click!");

    }

    /**

     * 定义Fragment对话框对象cancel按钮点击时,要执行的方法。

     */

    publicvoid doNegativieClick(){

    Log.i("FragmentAlertDialog","Negative click");

    }

    /**

     * 定义Fragment对话框的静态类,继承DialogFragment类。

     */

    publicstaticclass MyAlertDialogFragmentextends DialogFragment{

    /**

     * 创建Fragment对话框实例

     * @param title:指定对话框的标题。

     * @returnFragment对话框实例。

     */

    publicstatic MyAlertDialogFragment newInstance(int title){

        MyAlertDialogFragment frag = new MyAlertDialogFragment();

        Bundle args = new Bundle();

        args.putInt("title", title);

        frag.setArguments(args);

        return frag;

    }

    /**

     * 覆写Fragment类的onCreateDialog方法,在FragmentDialogshow方法执行之后,

     * 系统会调用这个回调方法。

     */

    @Override

    public Dialog onCreateDialog(Bundle saveInstanceState){

        //获取对象实例化时传入的窗口标题。

        int title = getArguments().getInt("title");

        //返回提醒对话框。

        returnnew AlertDialog.Builder(getActivity())

                //设置标题图标

               .setIcon(R.drawable.alert_dialog_icon)

                //设置标题

               .setTitle(title)

                //设置确定按钮的标题和点击事件监听器。

               .setPositiveButton(R.string.alert_dialog_ok,       

                    new DialogInterface.OnClickListener() {

                    @Override

                    publicvoid onClick(DialogInterface dialog,int which) {

                         ((FragmentAlertDialog)getActivity()).doPositiveClick();

                        

                     }

                 }

                )

                 //设置取消按钮的标题和点击事件监听器。

             .setNegativeButton(R.string.alert_dialog_cancel,

                  new DialogInterface.OnClickListener() {                  

                        @Override

                        publicvoid onClick(DialogInterface dialog,int which) {

                            ((FragmentAlertDialog)getActivity()).doNegativieClick();

                           

                         }

                     }

             )

             //创建对话框

             .create();

    }

    }

}