AlertDialog的使用很普遍,在利用中當你想要用戶做出“是”或“否”或其它各式各樣的選擇時,為了保持在一樣的Activity和不改變用戶屏幕,就能夠使用AlertDialog.
https://github.com/JueYingCoder/AndroidUsefulExample_AlertDialog
這篇文章主要講授如何實現各種AlertDialog,文章比較長,如果能認真讀完,AlertDialog的各種用法應當就可以掌握了,下面是我們今天要實現的終究效果:
乍1看,在利用中我們見過很多千奇百怪的對話框,但仔細分析,它還是有規律可循的,不外乎那幾種,我們要學會從簡易處著手,抽絲剝繭來掌握1項看起來仿佛很復雜的功能。只要我們理清了基本邏輯,其他的根據需要適當改造就能夠為我們所用了!
AlertDialog基本的結構以下:
可以將對話框主要分為3個部份:上面區域是標題欄和圖標,中間區域是內容區,下方是button區;其他情勢各異的對話框也都是基于此的變體而已!
那末要創建1個對話框,我們需要做些甚么:
1,首先需要創建1個AlertDialog.Builder對象,基本語法:
AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(this);
2,創建alertDialogBuilder對象后,通過調用它的create()方法就能夠構造出1個對話框
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();//將dialog顯示出來
3,但是我們還有1個疑問,如何設置Dialog的其他屬性呢,也就是說怎樣控制標題,圖表區域,內容區域和button區域,我們自但是然的想到的是1系列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{
//對應各個button
private Button simpleDiaog;
private Button simpleListDiaog;
private Button singleChoiceDiaog;
private Button multiChoiceDiaog;
private Button customAdateprDiaog;
private Button customViewDiaog;
//聲明1個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點擊后彈出對應對話框,為了方便,各寫1個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()
: 根據我們前面所寫的基本語法,我們可以很快寫出下面這些代碼,唯1需要注意的就是監聽兩個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()
:前面的代碼很類似,唯1需要改變的就是將內容區域改成列表項:
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,然后需要覆寫其中4個方法,其中getView()方法負責顯示,所以我們還需要為它創建1個布局文件:
layout->custom_adapter.xml
<?xml version="1.0" encoding="utf⑻"?>
<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中需要1張圖片和String來填充我們剛定義好的layout;所以我們還需要在MainActivity中建立1個數據類: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的內容區域,我們首先需要建立1個布局文件:
layout->custom_view.xml
<?xml version="1.0" encoding="utf⑻"?>
<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;如果你已掌握了自定義adapter和自定義ListView的話可以試著實現刪除和置頂ListItem的功能。
Tips:編寫自定義ListView,監聽長按ListItem時彈出AlertDialog,并且實現點擊刪除能保證ListView中的Item刪除掉,并且能夠實現置頂功能