天天看點

UI元件-對話框

前言

不要嫌前進的慢,隻要一直在前進就好。

AlertDialog元件

AlertDialog的功能很強大,它生成的對話框可分為如下4個區域。

  • 圖示區
  • 标題區
  • 内容區
  • 按鈕區

從上面這個結構來看建立對話框需要以下幾步。

  1. 建立AlertDialog.Builder對象
  2. 調用AlertDialog.Builder的setTitle()或setCustomTitle()方法設定标題。
  3. 調用AlertDialog.Builder的setIcon()方法設定圖示。
  4. 調用AlertDialog.Builder的相關設定方法設定對話框内容。
  5. 調用AlertDialog.Builder的setPositiveButton()、setNegativeButton()或setNeutralButton()方法添加多個按鈕。
  6. 調用AlertDialog.Builder的create()方法建立AlertDialog對象,再調用AlertDialog對象的show()方法将該對話框顯示出來。

其中第4步設定對話框的内容有如下6種方法來指定。

  1. setMessage():設定對話框内容為簡單文本。
  2. setItems():設定對話框内容為簡單清單項。
  3. setSingleChoiceItems():設定對話框内容為單選清單項。
  4. setMultiChoiceItems():設定對話框内容為多選清單項。
  5. setAdapter():設定對話框内容為自定義清單項。
  6. setView():設定對話框内容為自定義View。

代碼示例

alertdialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/show"
        android:textSize="20dp"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="簡單對話框"
        android:onClick="simple"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="簡單清單項對話框"
        android:onClick="simpleList"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="單選清單項對話框"
        android:onClick="singleChoice"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="多選清單項對話框"
        android:onClick="multiChoice"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="自定義清單項對話框"
        android:onClick="customList"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="自定義View對話框"
        android:onClick="customView"
        />

</LinearLayout>
           
MainActivity.java
private AlertDialog.Builder setPositiveButton(AlertDialog.Builder builder)
    {
        //調用setPositiveButton方法添加“确定”按鈕
        return builder.setPositiveButton("确定", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                show.setText("單擊了【确定】按鈕!");
            }
        });
    }
    private AlertDialog.Builder setNegativeButton(AlertDialog.Builder builder)
    {
        //調用setPositiveButton方法添加“确定”按鈕
        return builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                show.setText("單擊了【取消】按鈕!");
            }
        });
    }
           
提示消息的對話框
public void simple(View v)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("簡單對話框")          //設定标題
                .setIcon(R.drawable.ic_launcher) //設定圖示
                .setMessage("對話框測試内容\n第二行内容");
        //AlertDialog.Builder添加确定按鈕
        setPositiveButton(builder);
        //AlertDialog.Builder添加取消按鈕
        setNegativeButton(builder)
        .create()
        .show();
    }
           
簡單清單項對話框
public void simpleList(View v)
    {
        final String items[] = {"西遊記","三國演義","水浒傳","紅樓夢"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                //設定對話框标題
                .setTitle("簡單清單項對話框")
                //設定圖示
                .setIcon(R.drawable.ic_launcher)
                //設定内容
                .setItems(items, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        show.setText("您選中了《" +  items[which] + "》");

                    }
                });
        //為AlertDialog。Builder添加“确定”按鈕
        setPositiveButton(builder);
        //為AlertDialog。Builder添加“取消”按鈕
        setNegativeButton(builder)
        .create()
        .show();
    }
           
單選清單項對話框
public void singleChoice(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                // 設定對話框标題
                .setTitle("單選清單項對話框")
                // 設定圖示
                .setIcon(R.drawable.ic_launcher)
                // 設定單選清單項,預設選中第二項
                .setSingleChoiceItems(items, 1, new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        show.setText("您選中了《" + items[which] + "》");
                    }
                });
        // 為AlertDialog。Builder添加“确定”按鈕
        setPositiveButton(builder);
        // 為AlertDialog。Builder添加“取消”按鈕
        setNegativeButton(builder)
        .create()
        .show();
    }
           
多選清單項對話框
public void multiChoice(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                // 設定對話框标題
                .setTitle("多選清單項對話框")
                // 設定圖示
                .setIcon(R.drawable.ic_launcher)
                // 設定多選清單項,預設勾選第三項
                .setMultiChoiceItems(items, new boolean[]{false, false, true, false},null);
        // 為AlertDialog。Builder添加“确定”按鈕
        setPositiveButton(builder);
        // 為AlertDialog。Builder添加“取消”按鈕
        setNegativeButton(builder)
        .create()
        .show();
    }
           
自定義清單項對話框
public void customList(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                // 設定對話框标題
                .setTitle("自定義清單項對話框")
                // 設定圖示
                .setIcon(R.drawable.ic_launcher)
                // 設定自定義清單項
                .setAdapter(new ArrayAdapter<String>(this, R.layout.array_item, items), null);
        // 為AlertDialog。Builder添加“确定”按鈕
        setPositiveButton(builder);
        // 為AlertDialog。Builder添加“取消”按鈕
        setNegativeButton(builder)
        .create()
        .show();
    }

           
自定義View對話框
public void customView(View v) {

        TableLayout loginForm = (TableLayout) getLayoutInflater().inflate(R.layout.login, null);

        new AlertDialog.Builder(this)
        .setIcon(R.drawable.ic_launcher)
        .setTitle("自定義View對話框")
        .setView(loginForm)
        .setPositiveButton("登陸", null)
        .setNegativeButton("取消", null)
        .create()
        .show();
    }
           

效果

UI元件-對話框

Screenshot_20171024-093905.png

UI元件-對話框

Screenshot_20171024-094839.png

UI元件-對話框

Screenshot_20171024-095730.png

UI元件-對話框

Screenshot_20171024-100031.png

UI元件-對話框

Screenshot_20171024-100446.png

UI元件-對話框

Screenshot_20171024-101745.png

提示

不僅setAdapter()方法可以接受Adapter作為參數,setSingleChoice方法也可以接受Adapter作為參數,也可以傳入Cursor(相當于資料庫查詢結果集)作為參數。

PopupWindow元件

PopupWindow元件與AlertDialog功能相似,主要的差別就是AlertDialog不能指定顯示位置,隻能預設顯示在螢幕中間。而PopupWindow元件更加靈活,任意位置都可以顯示。

使用PoppupWindow建立對話框隻要如下兩步。

  • 調用PopupWindow的構造器建立PopupWindow對象。
  • 調用PopupWindow的showAsDropDown(View v)方法将PopupWindow作為v元件的下拉元件顯示;或調用PopupWindow的showAtLocation()方法将PopupWindow在指定位置顯示出來。

使用showAtLocation()方法顯示
popup_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
  >
    <Button
        android:id="@+id/bn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="彈出POPUP視窗"
        />
</LinearLayout>

           
popup.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:orientation="vertical"
     >
    <ImageView
        android:layout_width="500dp"
        android:layout_height="wrap_content"
        android:src="@drawable/kaola"
        />
    <Button
        android:layout_gravity="center_horizontal"
        android:id="@+id/close"
        android:text="關閉"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>
           
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup_main);

        //加載R.layout.popup對應的界面布局檔案
        View root = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup, null);
        //建立PopupWindow對象
        final PopupWindow popup = new PopupWindow(root,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,true);
        Button button = (Button) findViewById(R.id.bn);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                View rootView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_main, null);
                //将PopupWindow顯示在指定位置
                popup.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
            }
        });
        //擷取PopupWindow中的“關閉”按鈕
        root.findViewById(R.id.close).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                //關閉PopupWindow
                popup.dismiss();
            }
        });
    }
}
           
使用showAsDropDown()方法顯示
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:textColor="#50484b"
            android:padding="10dp"
            android:text="傳回"
            />
        <TextView
            android:id="@+id/menu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:textColor="#50484b"
            android:padding="10dp"
            android:text="菜單"
            />

    </RelativeLayout>


</LinearLayout>

           
popup_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="2dp" >

    <View
        android:layout_width="match_parent"
        android:layout_height="2.25dp"
        android:background="#fa7829" />

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="halo" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#f00" />

    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="halo1" />

</LinearLayout>
           
public class MainActivity extends Activity {

    private PopupWindow popup;
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

         tv = (TextView) findViewById(R.id.menu);
         tv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                showPopupWindow();

            }
        });
    }
    private void showPopupWindow() {
        View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_layout, null);
        popup = new PopupWindow(contentView);
        popup.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        TextView tv1 = (TextView) contentView.findViewById(R.id.tv1);
        TextView tv2 = (TextView) contentView.findViewById(R.id.tv2);

        tv1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "tv1", Toast.LENGTH_SHORT).show();
                popup.dismiss();
            }
        });
        tv2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "tv2", Toast.LENGTH_SHORT).show();
                popup.dismiss();
            }
        });

        popup.showAsDropDown(tv);

    }
}
           

UI元件-對話框

Screenshot_20171024-132525.png

UI元件-對話框

Screenshot_20171024-135937.png

PopupWindow最基本的三個條件是一定要設定contentView,width,height,不然PopupWindow不顯示。

DatePickerDialog和TimerPickerDialog元件

這兩個元件的功能和用法非常簡單,隻要如下兩步即可。

  • 通過new關鍵字建立DatePickerDialog、TimerPickerDialog執行個體,調用它們的show()方法即可将日期選擇對話框、時間選擇對話框顯示出來。
  • 為DatePickerDialog、TimePickerDialog綁定監聽器,這樣可以保證使用者設定事件時觸發監聽器。

pickerdialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <EditText
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="bt_datepicker"
        android:text="日期選擇對話框"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="bt_timepicker"
        android:text="時間選擇對話框"
        />

</LinearLayout>

           
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pickerdialog);

    }

    public void bt_timepicker(View v)
    {
        Calendar c = Calendar.getInstance();
        //建立一個DatePickerDialog對話框執行個體
        new DatePickerDialog(MainActivity.this,
                new OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        EditText show = (EditText) findViewById(R.id.show);
                        show.setText("您選擇了:" + year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
                    }
                },
                c.get(Calendar.YEAR),
                c.get(Calendar.MONTH),
                c.get(Calendar.DAY_OF_MONTH)).show();
    }


    public void bt_datepicker(View v)
    {
        Calendar c = Calendar.getInstance();

        new TimePickerDialog(MainActivity.this, new OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                EditText show = (EditText) findViewById(R.id.show);
                show.setText("您選擇了:" + hourOfDay + "時" + minute + "分");
            }
        }
        ,c.get(Calendar.HOUR_OF_DAY)
        ,c.get(Calendar.MINUTE)
        , true).show();//true表示24小時制
    }
}
           

UI元件-對話框

Screenshot_20171024-142038.png

UI元件-對話框

Screenshot_20171024-142044.png

ProgressDialog元件

ProgressDialog代表了進度對話框。使用ProgressDialog建立進度對話框有如下兩種方式。

  • 如果隻是建立簡單的進度對話框,那麼調用ProgressDialog提供的靜态show()方法顯示對話框即可。
  • 建立ProgressDialog,然後調用方法對對話框裡的進度條進行設定,設定完成後将對話框顯示出來即可。

對進度對話框進行設定的方法如下。

  • setIndeterminate(boolean indeterminate):設定對話框裡的進度條不顯示進度值。
  • setMax(int max):設定對話框裡進度條的最大值。
  • setMessage(CharSequence message):設定對話框裡的提示消息。
  • setProgress(int value);設定對話框裡進度條的進度值。
  • setProgressStyle(int style):設定對話框裡進度條的風格。

progressdialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="show_Progress1"
        android:text="環形進度條"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="show_Progress2"
        android:text="不顯示進度的進度條"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="show_Progress3"
        android:text="顯示進度的進度條"
        />

</LinearLayout>

           
public class MainActivity extends Activity {

    final static int MAX_PROGRESS = 100;
    //該程式模拟填充長度為100的數組
    private int[] data = new int[50];
    //記錄進度對話框的完成百分比
    int progressStatus = 0;
    int hasData = 0;
    ProgressDialog pd1,pd2;
    //定義一個負責更新進度的Handler
    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {

            //表明該消息是由該程式發送的
            if(msg.what == 1)
            {
                pd2.setProgress(progressStatus);
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.progressdialog);

    }

    public void show_Progress1(View v)
    {
        //調用靜态方法顯示環形進度條
        ProgressDialog.show(this, "任務執行中", "任務執行中,請等待",false,true);
    }
    public void show_Progress2(View v)
    {
        pd1 = new ProgressDialog(MainActivity.this);
        //設定對話框标題
        pd1.setTitle("任務執行中");
        //設定對話框顯示的内容
        pd1.setMessage("任務正在執行中,請等待。。。");
        //設定對話框能用"取消"按鈕關閉
        pd1.setCancelable(true);
        //設定對話框的進度條風格
        pd1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //設定對話框的進度條是否顯示進度
        pd1.setIndeterminate(false);
        pd1.show();
    }
    public void show_Progress3(View v)
    {
        //将進度條的完成進度重設為0
        progressStatus = 0;
        //重新開始填充數組
        hasData = 0;
        pd2 = new ProgressDialog(MainActivity.this);
        //設定對話框的标題
        pd2.setTitle("任務完成百分比");
        //設定對話框的顯示内容
        pd2.setMessage("耗時任務的完成百分比");
        //設定對話框不能用"取消"按鈕關閉
        pd2.setCancelable(false);
        //設定對話框的進度條風格
        pd2.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        //設定對話框的進度條是否顯示進度條
        pd2.setIndeterminate(false);
        pd2.show();
        new Thread()
        {
            public void run()
            {
                while(progressStatus < MAX_PROGRESS)
                {
                    //擷取耗時操作的完成百分比
                    progressStatus = MAX_PROGRESS * doWork() / data.length;
                    //發送空消息到Handler
                    handler.sendEmptyMessage(1);
                }
                //如果任務已完成
                if(progressStatus >= MAX_PROGRESS)
                {
                    //關閉對話框
                    pd2.dismiss();
                }
            }
        }.start();
    }

    public int doWork() {

        //為數組元素指派
        data[hasData++] = (int)(Math.random() * 100);
        try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return hasData;
    }
}
           

UI元件-對話框

progress1.PNG

UI元件-對話框

Screenshot_20171024-145850.png

UI元件-對話框

Screenshot_20171024-145327.png

繼續閱讀