我們在android的sdk中有apiDemos這個範例
在其中APP/Dialog中有一項 Text Entry Dialog 範例
用於自定義的 Dialog ,但其範例中並沒有真的把 EditText中的值給取出來
只有展示dialog的空殼。
作為一個android的新手
要取出其中EditText值的時候很自然的就會使用findViewById來取得裡面的值,如下
EditText username_edit = (EditText) findViewById(R.id.username_edit);
但這一行要放在哪裡呢?
我試過各種方式,將它放在onCreate() 或是 onClick()裡面都不能用。
後來在網上有查到,原來 findViewById() 這個函式
"Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle)."
也就是只能抓到一開始在onCreate(Bundle)函式中 設定的 xml layout中
再一查,原來view中也有 findViewById這個函式。
所以就將此EditText 定義為
EditText username_edit = (EditText) textEntryView.findViewById(R.id.username_edit);
==
apiDemos片段的程式修改如下:
case DIALOG_TEXT_ENTRY:
// This example shows how to add a custom layout to an AlertDialog
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
EditText username_edit = (EditText) textEntryView.findViewById(R.id.username_edit);
return new AlertDialog.Builder(AlertDialogSamples.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_text_entry)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String s = usernam_edit.getText().toString();
/* User clicked OK so do some stuff */
}
})
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked cancel so do some stuff */
}
})
.create();
==============================
即可在dialog中正常使用元件了!