2012-08-24 45 views

回答

19

創建自定義對話框

如果你想爲一個對話框,以定製的設計,您可以用佈局和widget元素的對話窗口中創建自己的佈局。在定義佈局之後,將根視圖對象或佈局資源ID傳遞給setContentView(View)。

例如,創建右側所示的對話框:

創建保存爲custom_dialog.xml的XML佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:id="@+id/layout_root" 
       android:orientation="horizontal" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       android:padding="10dp" 
       > 
    <ImageView android:id="@+id/image" 
       android:layout_width="wrap_content" 
       android:layout_height="fill_parent" 
       android:layout_marginRight="10dp" 
       /> 
    <TextView android:id="@+id/text" 
       android:layout_width="wrap_content" 
       android:layout_height="fill_parent" 
       android:textColor="#FFF" 
       /> 
</LinearLayout> 

此XML定義了一個ImageView的和的LinearLayout內一個TextView。 設置上述佈局對話框的內容視圖並定義的ImageView和TextView的元素內容:

Context mContext = getApplicationContext(); 
Dialog dialog = new Dialog(mContext); 

dialog.setContentView(R.layout.custom_dialog); 
dialog.setTitle("Custom Dialog"); 

TextView text = (TextView) dialog.findViewById(R.id.text); 
text.setText("Hello, this is a custom dialog!"); 
ImageView image = (ImageView) dialog.findViewById(R.id.image); 
image.setImageResource(R.drawable.android); 

後您實例的對話框中,設置自定義佈局對話框的內容視圖用的setContentView(INT),傳遞它是佈局資源ID。既然對話框具有已定義的佈局,您可以使用findViewById(int)從佈局中捕獲視圖對象並修改其內容。 就是這樣。您現在可以按照顯示對話框中所述顯示對話框。 使用基礎Dialog類進行的對話框必須有標題。如果您不調用setTitle(),則用於標題的空間保持空白,但仍然可見。如果您根本不需要標題,那麼您應該使用AlertDialog類創建自定義對話框。但是,由於AlertDialog是使用AlertDialog.Builder類創建的最簡單的方法,因此無法訪問上面使用的setContentView(int)方法。相反,你必須使用setView(View)。該方法接受一個View對象,所以你需要從XML中擴展布局的根視圖對象。

要擴充XML佈局,請使用getLayoutInflater()(或getSystemService())檢索LayoutInflater,然後調用inflate(int,ViewGroup),其中第一個參數是佈局資源ID,第二個參數是ID根視圖。此時,您可以使用膨脹的佈局在佈局中查找View對象,併爲ImageView和TextView元素定義內容。然後實例化AlertDialog.Builder並使用setView(View)爲對話框設置充氣佈局。

下面是一個例子,在AlertDialog創建自定義佈局:

AlertDialog.Builder builder; 
AlertDialog alertDialog; 

Context mContext = getApplicationContext(); 
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View layout = inflater.inflate(R.layout.custom_dialog, 
           (ViewGroup) findViewById(R.id.layout_root)); 

TextView text = (TextView) layout.findViewById(R.id.text); 
text.setText("Hello, this is a custom dialog!"); 
ImageView image = (ImageView) layout.findViewById(R.id.image); 
image.setImageResource(R.drawable.android); 

builder = new AlertDialog.Builder(mContext); 
builder.setView(layout); 
alertDialog = builder.create(); 

使用一個AlertDialog您的自定義佈局使您可以利用的優勢內置AlertDialog功能,比如管理按鈕,選擇列表,一個標題,一個圖標等等。

有關更多信息,請參閱Dialog和AlertDialog.Builder類的參考文檔。

+4

感謝您對我的搜索引擎優化,我會在角落裏坐幾分鐘的時間來處罰。 –