【轉】 Android常用實例—Alert Dialog的使用


Android常用實例—Alert Dialog的使用

AlertDialog的使用很普遍,在應用中當你想要用戶做出“是”或“否”或者其它各式各樣的選擇時,為了保持在同樣的Activity和不改變用戶屏幕,就可以使用AlertDialog.

代碼地址

https://github.com/JueYingCoder/AndroidUsefulExample_AlertDialog

這篇文章主要講解如何實現各種AlertDialog,文章比較長,如果能認真讀完,AlertDialog的各種用法應該就能掌握了,下面是我們今天要實現的最終效果:

這里寫圖片描述

乍一看,在應用中我們見過很多千奇百怪的對話框,但仔細分析,它還是有規律可循的,不外乎那幾種,我們要學會從簡易處着手,抽絲剝繭來掌握一項看起來似乎很復雜的功能。只要我們理清了基本邏輯,其他的根據需要適當改造就可以為我們所用了! 
AlertDialog基本的結構如下: 
這里寫圖片描述

可以將對話框主要分為三個部分:上面區域是標題欄和圖標,中間區域是內容區,下方是button區;其他形式各異的對話框也都是基於此的變體而已!

那么要創建一個對話框,我們需要做些什么:

1,首先需要創建一個AlertDialog.Builder對象,基本語法:

AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(this);

2,創建alertDialogBuilder對象后,通過調用它的create()方法就可以構造出一個對話框

AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show();//將dialog顯示出來

3,但是我們還有一個疑問,如何設置Dialog的其他屬性呢,也就是說怎么控制標題,圖表區域,內容區域和button區域,我們自然而然的想到的是一系列set方法;事實上真是如此,通過調用alertDialogBuilder對象的setXX方法來實現:

alertDialogBuilder.setTitle();//設置標題 alertDialogBuilder.setIcon();//設置圖表 /*設置下方按鈕*/ alertDialogBuilder.setPositiveButton(); alertDialogBuilder.setNegativeButton(); alertDialogBuilder.setNeutralButton(); /*對話框內容區域的設置提供了多種方法*/ setMessage();//設置顯示文本 setItems();//設置對話框內容為簡單列表項 setSingleChoiceItems();//設置對話框內容為單選列表項 setMultiChoiceItems();//設置對話框內容為多選列表項 setAdapter();//設置對話框內容為自定義列表項 setView();//設置對話框內容為自定義View //設置對話框是否可取消 setCancelable(booleab cancelable); setCancelListener(onCancelListener);

綜上:對於AlertDialog的使用其實主要還是針對如何設置內容區域;

下面我們通過使用不同的內容區域的設置方法,實現幾個常用的對話框;
基本思路是在MainActivity中添加幾個Button,點擊后分別彈出對應的AlertDialog

步驟: 
1 .創建Android Project->”AlertDialogDemo” 
2 .編寫activity_main.xml布局文件 
3.編寫所需strings.xml 
4.編寫MainActivity中各方法

限於篇幅的問題,現只貼出關鍵性部分代碼,其余的請讀者自行實現; 
activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/btn_simple_dialog" android:text="@string/simple_dialog" android:textColor="#ffffff" android:textSize="18sp" android:background="#449F1D" android:layout_marginTop="10dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_simple_list_dialog" android:text="@string/simple_list_dialog" android:textColor="#ffffff" android:textSize="18sp" android:background="#449F1D" android:layout_marginTop="10dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_single_choice_dialog" android:text="@string/single_choice_dialog" android:textColor="#ffffff" android:textSize="18sp" android:background="#449F1D" android:layout_marginTop="10dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_multi_choice_dialog" android:text="@string/multi_choice_dialog" android:textColor="#ffffff" android:textSize="18sp" android:background="#449F1D" android:layout_marginTop="10dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_custom_adapter_dialog" android:text="@string/custom_adapter_dialog" android:textColor="#ffffff" android:textSize="18sp" android:background="#449F1D" android:layout_marginTop="10dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn_custom_view_dialog" android:text="@string/custom_view_dialog" android:textColor="#ffffff" android:textSize="18sp" android:background="#449F1D" android:layout_marginTop="10dp" android:layout_marginLeft="50dp" android:layout_marginRight="50dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>

布局效果:

這里寫圖片描述

strings.xml

<resources> <string name="app_name">ALertDialogDemo</string> <!-- 主界面布局所需要的字符串資源--> <string name="action_settings">Settings</string> <string name="simple_dialog">基本對話框</string> <string name="simple_list_dialog">簡單列表對話框</string> <string name="single_choice_dialog">單選項列表對話框</string> <string name="multi_choice_dialog">多選項列表對話框</string> <string name="custom_adapter_dialog">自定義Adapter對話框</string> <string name="custom_view_dialog">自定義View對話框</string> <!-- 對話框所需要的字符串資源--> <string name="dialog_message">這里是內容區域</string> <string name="postive_button">確定</string> <string name="negative_button">取消</string> <!-- 對話框提示信息字符串資源--> <string name="toast_postive">你點擊了確定按鈕</string> <string name="toast_negative">你點擊了取消按鈕</string> <string name="text">自定義Adapter的內容</string> </resources>

MainActivity.Java

public class MainActivity extends ActionBarActivity implements View.OnClickListener{ //對應各個button private Button simpleDiaog; private Button simpleListDiaog; private Button singleChoiceDiaog; private Button multiChoiceDiaog; private Button customAdateprDiaog; private Button customViewDiaog; //聲明一個AlertDialog構造器 private AlertDialog.Builder builder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //實例化控件 simpleDiaog= (Button) findViewById(R.id.btn_simple_dialog); simpleListDiaog= (Button) findViewById(R.id.btn_simple_list_dialog); singleChoiceDiaog= (Button) findViewById(R.id.btn_single_choice_dialog); multiChoiceDiaog= (Button) findViewById(R.id.btn_multi_choice_dialog); customAdateprDiaog= (Button) findViewById(R.id.btn_custom_adapter_dialog); customViewDiaog= (Button) findViewById(R.id.btn_custom_view_dialog); //監聽點擊事件 simpleDiaog.setOnClickListener(this); simpleListDiaog.setOnClickListener(this); singleChoiceDiaog.setOnClickListener(this); multiChoiceDiaog.setOnClickListener(this); customAdateprDiaog.setOnClickListener(this); customViewDiaog.setOnClickListener(this); } /** * * 每個button點擊后彈出對應對話框,為了方便,各寫一個showXXDialog()方法 */ @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_simple_dialog: showSimpleDialog(view); break; case R.id.btn_simple_list_dialog: showSimpleListDialog(view); break; case R.id.btn_single_choice_dialog: showSingleChoiceDialog(view); break; case R.id.btn_multi_choice_dialog: showMultiChoiceDialog(view); break; case R.id.btn_custom_adapter_dialog: showCustomAdapterDialog(view); break; case R.id.btn_custom_view_dialog: showCustomViewDialog(view); break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }

上述代碼都比較簡單,現在我們真正關心的就是如何去具體實現showXXDialog;


1.showSimpleDialog(): 根據我們前面所寫的基本語法,我們可以很快寫出下面這些代碼,唯一需要注意的就是監聽兩個button,由於這是最基本也是最核心的AlertDialog,所以只要掌握了這個其他的alertDialog也就相對簡單了;

//顯示基本Dialog
    private void showSimpleDialog(View view) {
        builder=new AlertDialog.Builder(this); builder.setIcon(R.mipmap.ic_launcher); builder.setTitle(R.string.simple_dialog); builder.setMessage(R.string.dialog_message); //監聽下方button點擊事件 builder.setPositiveButton(R.string.postive_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getApplicationContext(),R.string.toast_postive,Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getApplicationContext(), R.string.toast_negative, Toast.LENGTH_SHORT).show(); } }); //設置對話框是可取消的 builder.setCancelable(true); AlertDialog dialog=builder.create(); dialog.show(); }

實現效果:

這里寫圖片描述

2,showSimpleListDialog():前面的代碼很相似,唯一需要改變的就是將內容區域改為列表項:

private void showSimpleListDialog(View view) { builder=new AlertDialog.Builder(this); builder.setIcon(R.mipmap.ic_launcher); builder.setTitle(R.string.simple_list_dialog); /** * 設置內容區域為簡單列表項 */ final String[] Items={"Items_one","Items_two","Items_three"}; builder.setItems(Items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getApplicationContext(), "You clicked "+Items[i], Toast.LENGTH_SHORT).show(); } }); builder.setCancelable(true); AlertDialog dialog=builder.create(); dialog.show(); }

實現效果:

這里寫圖片描述

3,showSingleChoiceDialog():注意setSingleChoiceItems()內部各參數的意義

    private void showSingleChoiceDialog(View view) { builder=new AlertDialog.Builder(this); builder.setIcon(R.mipmap.ic_launcher); builder.setTitle(R.string.single_choice_dialog); /** * 設置內容區域為單選列表項 */ final String[] items={"Items_one","Items_two","Items_three"}; builder.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getApplicationContext(), "You clicked "+items[i], Toast.LENGTH_SHORT).show(); } }); builder.setCancelable(true); AlertDialog dialog=builder.create(); dialog.show(); }

實現效果:

這里寫圖片描述

4showMultiCHoiceDialog():

private void showMultiChoiceDialog(View view) { builder=new AlertDialog.Builder(this); builder.setIcon(R.mipmap.ic_launcher); builder.setTitle(R.string.simple_list_dialog); /** * 設置內容區域為多選列表項 */ final String[] items={"Items_one","Items_two","Items_three"}; builder.setMultiChoiceItems(items, new boolean[]{true, false, true}, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean b) { Toast.makeText(getApplicationContext(),"You clicked "+items[i]+" "+b,Toast.LENGTH_SHORT).show(); } }); builder.setCancelable(true); AlertDialog dialog=builder.create(); dialog.show(); }

實現效果:

這里寫圖片描述

5,showCustomAdapterDialog():

這部分涉及到自定義Adapter,如果對這部分不太了解,也不用灰心,在后面的文章中我會單獨講解Adapter這部分。在這里我們只需要了解自定義Adapter需要繼承自BaseAdapter,然后需要覆寫其中四個方法,其中getView()方法負責顯示,所以我們還需要為它創建一個布局文件: 
layout->custom_adapter.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:background="#dddddd" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:layout_marginBottom="10dp" android:layout_marginRight="15dp" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/id_image" android:layout_width="60dp" android:layout_height="60dp" /> <TextView android:textColor="#554995" android:id="@+id/id_text" android:layout_marginLeft="20dp" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

布局效果:

這里寫圖片描述

然后我們在需要在MainActivity.java中實現我們自定義的Adapter:

private class CustomAdapter extends BaseAdapter { private List<ItemBean> items; private LayoutInflater inflater; private ImageView image; private TextView text; public CustomAdapter(List<ItemBean> items, Context context) { this.items = items; this.inflater = LayoutInflater.from(context); } @Override public int getCount() { return items.size(); } @Override public Object getItem(int i) { return items.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { if(view==null){ view=inflater.inflate(R.layout.custom_adapter,null); image= (ImageView) view.findViewById(R.id.id_image); text= (TextView) view.findViewById(R.id.id_text); } image.setImageResource(items.get(i).getImageId()); text.setText(items.get(i).getMessage()); return view; } }

我們在這里使用了List items;是因為Adapter中需要一張圖片和String來填充我們剛定義好的layout;所以我們還需要在MainActivity中建立一個數據類:ItemBean:

private class ItemBean{ private int imageId; private String message; public ItemBean(int imageId, String message) { this.imageId = imageId; this.message = message; } public String getMessage() { return message; } public int getImageId() { return imageId; } public void setImageId(int imageId) { this.imageId = imageId; } public void setMessage(String message) { this.message = message; } } private void showCustomAdapterDialog(View view){ builder=new AlertDialog.Builder(this); builder.setIcon(R.mipmap.ic_launcher); builder.setTitle(R.string.custom_adapter_dialog); /** * 設置內容區域為自定義adapter */ List<ItemBean> items=new ArrayList<>(); items.add(new ItemBean(R.mipmap.icon,"You can call me xiaoming")); items.add(new ItemBean(R.mipmap.ic_launcher, "I'm android xiao")); CustomAdapter adapter=new CustomAdapter(items,getApplicationContext()); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getApplicationContext(),"You clicked"+i,Toast.LENGTH_SHORT).show(); } }); builder.setCancelable(true); AlertDialog dialog=builder.create(); dialog.show(); }

實現效果:

這里寫圖片描述

6,showCustomViewDialog() 
為了實現自定義View的內容區域,我們首先需要建立一個布局文件: 
layout->custom_view.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" android:gravity="center" android:background="#25AE90"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="60dp" android:layout_marginLeft="60dp"> <TextView android:text="用戶名" android:layout_marginRight="10dp" android:textSize="20sp" android:textColor="#ffffff" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:layout_width="0dp" android:layout_weight="1" android:layout_height="40dp" android:background="#ffffff"/> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginRight="60dp" android:layout_marginLeft="60dp"> <TextView android:text="密 碼" android:layout_marginRight="10dp" android:textSize="20sp" android:textColor="#ffffff" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:layout_width="0dp" android:layout_weight="1" android:layout_height="40dp" android:background="#ffffff"/> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginRight="60dp" android:layout_marginLeft="60dp"> <Button android:text="登 錄" android:textColor="#25AE90" android:background="#ECEEF1" android:layout_width="0dp" android:layout_marginRight="10dp" android:layout_weight="1" android:layout_height="wrap_content" /> <Button android:text="取 消" android:textColor="#25AE90" android:background="#ECEEF1" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout>

布局效果:

這里寫圖片描述

實現showCustomViewDialog()

private void showCustomViewDialog(View view){ builder=new AlertDialog.Builder(this); builder.setIcon(R.mipmap.ic_launcher); builder.setTitle(R.string.custom_view_dialog); /** * 設置內容區域為自定義View */ LinearLayout loginDialog= (LinearLayout) getLayoutInflater().inflate(R.layout.custom_view,null); builder.setView(loginDialog); builder.setCancelable(true); AlertDialog dialog=builder.create(); dialog.show(); }

實現效果:

這里寫圖片描述


總結:

  • AlertDialog基本用法 :需要掌握AlertDialog的創建過程,理解Builder模式;
  • 內容區域 :AlertDialog的難點就在於設計合適的內容區域;
  • 自定義布局 :很多時候我們都需要按照自己的意願去定制AlertDialog內容區域的顯示形式,這就需要我們掌握自定義Adapter和自定義View的用法,而這兩部分也是一個難點,要講的話又是另一個專題了;

作為文章的結束;為了檢驗我們是否已經掌握了AlertDialog的各種用法,我們可以試着實現以下微信中的AlertDialog;如果你已經掌握了自定義adapter和自定義ListView的話可以試着實現刪除和置頂ListItem的功能。

    Tips:編寫自定義ListView,監聽長按ListItem時彈出AlertDialog,並且實現點擊刪除能保證ListView中的Item刪除掉,並且能夠實現置頂功能

這里寫圖片描述

 

from:http://blog.csdn.net/qwm8777411/article/details/45420451


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM