問題描述
我的自定義對話框有問題.
我的對話框由 TextView
、EditText
和Ok"按鈕組成.單擊確定"后,它應(yīng)該從 EditText 字段中獲取文本并將其分配給 Activity 中定義的字符串變量名稱".
一切似乎都正常,沒有錯(cuò)誤等,但是文本"始終是一個(gè)空字符串.
我閱讀了一些有關(guān)此類問題的主題,但是我不確定我應(yīng)該在這里進(jìn)行哪些調(diào)整.
我對 Android 編程很陌生,所以如果有人能向我解釋這個(gè)問題,我將不勝感激.提前致謝.
I have a problem with a custom dialog.
My dialog consists of a TextView
, EditText
and an "Ok" Button. After clicking "Ok", it should get the text from EditText field and assign it to the String variable "name" defined in the Activity.
Everything seems to work, no errors etc, however "text" is always an empty String.
I read some topics about such problems, however I'm not really sure what adjustments I should make here.
I'm quite new to Android programming, so I'd be grateful if somebody could explain the problem to me. Thanks in advance.
final Dialog dialog = new Dialog(MyActivity.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Title");
final View layout = View.inflate(this, R.layout.custom_dialog, null);
Button button = (Button) dialog.findViewById(R.id.dialog_ok);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText edit=(EditText)layout.findViewById(R.id.dialog_edit);
String text=edit.getText().toString();
name=text;
dialog.dismiss();
}
});
dialog.show();
推薦答案
您正在對不需要的布局進(jìn)行膨脹.如您所見,我修復(fù)了您的代碼,我刪除了您的膨脹行并更改了您嘗試查找 EditText 視圖的行.
You are inflating a layout where it is not needed. I fixed your code as you see I removed your line where it inflates and changed the line where you try to find the EditText view.
final Dialog dialog = new Dialog(MyActivity.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Title");
Button button = (Button) dialog.findViewById(R.id.dialog_ok);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText edit=(EditText)dialog.findViewById(R.id.dialog_edit);
String text=edit.getText().toString();
dialog.dismiss();
name=text;
}
});
dialog.show();
這篇關(guān)于Android - 自定義對話框 - 無法從 EditText 獲取文本的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!