星期一, 10月 03, 2011

Creating a Custom Dialog

Android應用程式學習筆記

Creating a Custom Dialog

如果你想客製化設計對話框,你可以用布局和部件為對話框視窗建立自己的布局。在已定義你的布局後,傳入根視圖物件或是布局來源ID到setContentView(View)。

例子,建立右圖所示的對話框。

1.建立XML布局文件custom_dialog.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和TextView以及LinearLayout。

2.設置對話框的佈局為上述的布局文件並定義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)取得布局的Veiw物件並修改內容。

3.顯示對話框。


以Dialog類為基礎的對話框必須有標題,如果你不呼叫setTitle(),顯示標題的空間就會是空的,但是視可見的。如果你不想要有標題,你應該使用AlertDialog類建立客製化對話框。然而,因為用AlertDialog.Builder類建立AlertDialog是最簡單的,不需要setContentView(int)方法,取而代之,你必須呼叫setView(View)方法。該方法接收一個View物件,所以你需要從XML建立布局。

擴展XML布局,getLayoutInflater()取得LayoutInflater物件(或是getSystemService()),然後呼叫inflate(int , ViewGroup)方法,第一個參數是布局資源的ID,第二個參數是根View物件的ID。在此處,你可以在以擴展的布局中找到View物件並定義ImageView和TextView的內容。然後實體化AlertDialog.Builder並setView(view)設置對話框擴展布局。


AlertDialog.Builder builder;
AlertDialog alertDialog;
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(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();


沒有留言:

張貼留言