1. 程式人生 > >AlertDialog自定義整個佈局去掉原有的標題按鈕等

AlertDialog自定義整個佈局去掉原有的標題按鈕等

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

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

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

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

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

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

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

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

\

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

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

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

這裡介紹第二種方式。

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

程式碼如下:

[java] view plain copy  print?在CODE上檢視程式碼片派生到我的程式碼片
  1. String info = cityData.getPointerList().get(position).toString();  
  2. AlertDialog alertDialog = new AlertDialog.Builder(CityActivity.this).create();  
  3. alertDialog.show();  
  4. Window window = alertDialog.getWindow();  
  5. window.setContentView(R.layout.dialog_main_info);  
  6. TextView tv_title = (TextView) window.findViewById(R.id.tv_dialog_title);  
  7. tv_title.setText("詳細資訊");  
  8. TextView tv_message = (TextView) window.findViewById(R.id.tv_dialog_message);  
  9. tv_message.setText(info);  

佈局檔案:

[html] view plain copy  print?在CODE上檢視程式碼片派生到我的程式碼片
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent"
  5.     android:background="#ffff"
  6.     android:orientation="vertical">
  7.     <TextView
  8.         android:id="@+id/tv_dialog_title"
  9.         android:layout_width="match_parent"
  10.         android:layout_height="wrap_content"
  11.         android:background="#7a7"
  12.         android:padding="8dp"
  13.         android:textColor="#eee"
  14.         android:textSize="20sp"
  15.         android:textStyle="bold"/>
  16.     <TextView
  17.         android:id="@+id/tv_dialog_message"
  18.         android:layout_width="wrap_content"
  19.         android:layout_height="wrap_content"
  20.         android:layout_margin="5dp"
  21.         android:padding="3dp"/>
  22. </LinearLayout>


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

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