2012-03-19 89 views
25

我有一个简单的程序来显示一个对话框,其中包含edittext视图,并听取正/负按钮,在每个按钮中执行自定义操作(读取edittext并保存其内容到一个活动变量)。Android对话框界面获取内部对话框视图

当我看不到任何方法从对话框界面恢复当前对话框时(然后,我无法恢复对话框中的任何视图),问题就出现了。

也许这是一个noob问题,但经过一些谷歌搜索,我没有人回答它。

我的代码如下

LayoutInflater li = LayoutInflater.from(this); 
View myView = li.inflate(R.layout.my_layout, null); 

AlertDialog.Builder cDialog = new AlertDialog.Builder(this); 
cDialog.setView(myView); 
cDialog.setPositiveButton(R.string.start_download, new DialogInterface.OnClickListener() { 
    @Override 
    public void onClick(DialogInterface dialog, int which) { 
    //here the code to retrieve dialog 
    } 
}); 
cDialog.create(); 

约我在哪里可以找到任何线索?

回答

61

您可以检索从DialogonClick()与观点:

EditText edit = (EditText) ((AlertDialog) dialog).findViewById(R.id.the_id_of_view); 
+0

final AlertDialog dialog = adb.show(); 

所以,你可以在你的活动代码的任何地方调用你的对话框中的任意按钮嗨slukian。我试过这样做,但该实例来自DialogInterface类,而不是对话框。 DialogInterface不提供findViewById方法...所以检索给定对话框的内容是没有用的。 – user1220817 2012-03-19 14:05:09

+2

@ user1220817'dialog'参数是接收到点击的对话框。将它转换为'AlertDialog',然后像这样调用'findViewById()':EditText edit =(EditText)((AlertDialog)dialog).findViewById(R.id.editText1);'。 – Luksprog 2012-03-19 14:20:45

+0

噢,真好!非常感谢你,没有注意到DialogInterface可以直接对话。再次谢谢你 :) – user1220817 2012-03-19 14:31:48

13

在我的代码以这种方式运行完美:

public void onClick(DialogInterface dialog, int which) { 

    Dialog dialog2 =Dialog.class.cast(dialog); 
    EditText edit = (EditText) dialog2.findViewById(R.id.myedittext); 

} 

欢呼

4

您已经有了参考查看包含编辑文本的内容。为什么不直接使用它?只要确保您使视图最终确定,以便您可以在匿名课程中访问它。

LayoutInflater li = LayoutInflater.from(this); 
final View myView = li.inflate(R.layout.my_layout, null); 
// don't forget to mark myView as final 

AlertDialog.Builder cDialog = new AlertDialog.Builder(this); 
cDialog.setView(myView); 
cDialog.setPositiveButton(R.string.start_download, new DialogInterface.OnClickListener() { 
    @Override 
    public void onClick(DialogInterface dialog, int which) { 
    //here the code to retrieve dialog 
    EditText edit = (EditText) myView.findViewById(R.id.the_id_of_view); 
    } 
}); 
cDialog.create(); 
-1

您可以从方法show() alertBuidler返回对话框。如下

AlertDialog.Builder adb = new AlertDialog.Builder(YourActivity.this); 
//...code to add methods setPositive an setNegative buttons 

呼叫的adbshow()方法,并得到Dialog

dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();//or 
dialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick();//or 
dialog.getButton(DialogInterface.BUTTON_NEUTRAL).performClick();