標籤:android alertdialo 執行個體
Android常用執行個體—Alert Dialog的使用
AlertDialog的使用很普遍,在應用中當你想要使用者做出“是”或“否”或者其它各式各樣的選擇時,為了保持在同樣的Activity和不改變使用者螢幕,就可以使用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" />
布局效果:
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{//對應各個buttonprivate Button simpleDiaog;private Button simpleListDiaog;private Button singleChoiceDiaog;private Button multiChoiceDiaog;private Button customAdateprDiaog;private Button customViewDiaog;//聲明一個AlertDialog構造器private AlertDialog.Builder builder;@Overrideprotected 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()方法 */@Overridepublic 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; }}@Overridepublic boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true;}}
上述代碼都比較簡單,現在我們真正關心的就是如何去具體實現showXXDialog;
1.showSimpleDialog(): 根據我們前面所寫的基本文法,我們可以很快寫出下面這些代碼,唯一需要注意的就是監聽兩個button,由於這是最基本也是最核心的AlertDialog,所以只要掌握了這個其他的alertDialog也就相對簡單了;
//顯示基本Dialogprivate 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();}
實現效果:
4,showMultiCHoiceDialog():
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" />
布局效果:
然後我們在需要在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>
布局效果:
實現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刪除掉,並且能夠實現置頂功能
- 微博:@JueYingCoder,
- 個人首頁:Coder:程式員&&工科男的日常,
Android常用執行個體—Alert Dialog的使用