[Android] AlertDialog-嵌入客製化表單

文章AlertDialog-元件建立與顯示說明基本AlertDialog元件是由title、message所組成,實際應用情況是將特定訊息發送給使用者,並按下確認鈕使AlertDialog消失,上述應用都屬於單向互動,使用者只負責接收系統傳遞的訊息,但如果要作到雙向互動(如下圖),基本的AlertDialog是無法達成的



本文章將藉由LayoutInflater類別將Layout XML檔案轉換為View object,再透過AlertDialog類別的setView方法將其外觀設定為該custom view

範例情境:
AlertDialog顯示使用者名稱表單,完成輸入送出表單內容

程式碼說明:
一、建立輸入表單XML檔(login_view.xml),包含EditText和Button



二、以from(Context)取得目前Context LayoutInflater instance
LayoutInflater inflater = LayoutInflater.from(Alert.this);

三、利用inflate(int resource, ViewGroup root)將XML描述的Layout轉換為View Object,resource為XML檔案來源,在本例中就是R.layout.login_view;而root為選擇性參數,你可以利用它指定被轉換View Object的root view
View login_view = inflater.inflate(R.layout.login_view,null);

四、產生AlertDialog並利用setView(View view),將轉換為view的login_view指定為其layout
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("新增使用者");
builder.setMessage("請輸入使用者名稱:");
builder.setView(login_view);
AlertDialog dialog = builder.create();
dialog.show();

五、執行simulator,就會成功看到AlertDialog嵌入使用者名稱輸入的表單


完整程式碼:
package com.Alert;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

public class Alert extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
        
      //-----------取得Login Layout reference----------
      LayoutInflater inflater = LayoutInflater.from(Alert.this);
      View login_view = inflater.inflate(R.layout.login_view,null);
     
      //-----------產生登入視窗--------
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setTitle("新增使用者");
      builder.setMessage("請輸入使用者名稱:");
      builder.setView(textEntryView);  
      final AlertDialog dialog = builder.create();
      dialog.show();
    }
}

留言

這個網誌中的熱門文章

[Android] layout_weight的妙用-讓View的大小以百分比率顯示(proportionate size)

[Android] 內部儲存體(Internal Storage)的檔案系統讀寫(File I/O)

【海外婚紗】造型篇-我的超人新祕Sunny-Yang