Android 输入对话框返回输入值
我正为这件事揪心呢。
我有一个应用程序,当您按下菜单项时,我希望它显示一个输入警报对话框。当用户点击“确定”时,他们在对话框中的 EditText 中输入的文本需要返回以供稍后在活动中使用。
所以我想把:放在
name = input.getText().toString(); //input is an EditView which is the setView() of the dialog
“确定”按钮的 onClick 内部会起作用,但事实并非如此。 Eclipse 告诉我,我无法在 onClick 中设置 name,因为它不是最终的,但是如果我将 name 的定义更改为 Final,则它显然无法更改,因此无法在 onClick() 中设置。
这是这一点的完整代码:
String routeName = "";
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText inputName = new EditText(this);
alert.setView(inputName);
alert.setPositiveButton("Set Route Name", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
routeName = inputName.getText().toString();
}
});
alert.show();
我一定在这里做了一些非常愚蠢的事情,因为我已经用谷歌搜索了很长时间,发现没有其他人遇到同样的问题。
谁能启发我吗?
感谢您抽出时间,
InfinitiFizz
I'm pulling my hair out over this one.
I have an app that when you press a menu item, I want it to show an input alert dialog. When the user taps "OK" then the text they've entered into the EditText in the dialog wants to be returned to be used later in the activity.
So I thought putting:
name = input.getText().toString(); //input is an EditView which is the setView() of the dialog
Inside the onClick of the "Ok" button would work but it doesn't. Eclipse tells me I cant set name inside the onClick because it isn't final, but if I change name's definition to final it can't be changed obviously and so can't be set inside the onClick().
Here is the full code for this bit:
String routeName = "";
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText inputName = new EditText(this);
alert.setView(inputName);
alert.setPositiveButton("Set Route Name", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
routeName = inputName.getText().toString();
}
});
alert.show();
I must be doing something really stupid here because I've googled around for ages and found no-one else with the same problem.
Can anyone please enlighten me?
Thank you for your time,
InfinitiFizz
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上,您无法访问
onClick
中的任何内容,我认为这是一种匿名方法。你能做的就是了解背景并从中找到你的观点。它看起来像这样:您还可以使用
v
参数,例如通过在侦听器中调用v.getContext()
。Indeed, you can't get to just anything inside your
onClick
, which is an anonymous method I presume. What you can do is get the context and find your views from there. It would look something like this:You could also use the
v
argument, for instance by callingv.getContext()
in your listener.您可以将
routerName
设置为成员变量。You could make
routerName
a member variable.