Android進階之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. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns: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.   
  8.     <TextView  
  9.         android:id="@+id/tv_dialog_title"  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:background="#7a7"  
  13.         android:padding="8dp"  
  14.         android:textColor="#eee"  
  15.         android:textSize="20sp"  
  16.         android:textStyle="bold" />  
  17.   
  18.     <TextView  
  19.         android:id="@+id/tv_dialog_message"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:layout_margin="5dp"  
  23.         android:padding="3dp" />  
  24.   
  25. </LinearLayout>  


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

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

 

作者:jason0539

微博:http://weibo.com/2553717707

博客:http://blog.csdn.net/jason0539(轉載請說明出處)

發佈了4 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章