1. 程式人生 > >Android進階之AlertDialog自定義

Android進階之AlertDialog自定義

AlertDialog的自定義方式有很多種,這裡介紹兩種。

第一種是比較簡單的,只自定義內容。

一、簡單的AlertDialog(只顯示一段簡單的資訊,比如about us)

二、帶按鈕的AlertDialog(顯示提示資訊,讓使用者操作,比如exit時的警告框)

三、類似ListView的AlertDialog(展示內容,比如某人的一些註冊資訊)

四、類似RadioButton的AlertDialog(讓使用者選擇,單選)

五、類似CheckBox的AlertDialog(讓使用者多選)

六、自定義View的AlertDialog(當以上方式滿足不了你的需求,就要自定義了)

\

最後的第六種也就是自定義內容的實現方式,比如想做一個這種登入對話方塊,通過前五種方式明顯實現不了。

這時候就通過AlertDialog.Builder的setView把自己定義的登入介面設定進去,

而標題和按鈕都還用Android原生的,如果你是像這種方式的自定義,請進前面連結檢視最後一種方式。

這裡介紹第二種方式。

先看一下效果,左圖為原生的AlertDialog,右圖為自定義的AlertDialog,這樣自定義主要是為了讓介面更加統一。

程式碼如下:

String info = cityData.getPointerList().get(position).toString();
AlertDialog alertDialog = new AlertDialog.Builder(CityActivity.this).create();
alertDialog.show();
Window window = alertDialog.getWindow();
window.setContentView(R.layout.dialog_main_info);
TextView tv_title = (TextView) window.findViewById(R.id.tv_dialog_title);
tv_title.setText("詳細資訊");
TextView tv_message = (TextView) window.findViewById(R.id.tv_dialog_message);
tv_message.setText(info);

佈局檔案:

<?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:background="#ffff"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_dialog_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#7a7"
        android:padding="8dp"
        android:textColor="#eee"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_dialog_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:padding="3dp" />

</LinearLayout>


其實這裡自定義的主要目的就是想讓title的背景顏色顯示綠色,與activity的背景綠一致,比較和諧。

AlertDialog是Dialog的子類,也可以直接基於Dialog自定義。方法很多,用到了再嘗試。

作者:jason0539