Android 编辑文本到字符串
在Android上,我试图将Android 编辑文本到字符串,android,android-edittext,Android,Android Edittext,在Android上,我试图将Edittext转换为字符串。toString()方法不起作用,打印时playerName为null。是否有其他方法将edittext转换为字符串 AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setMessage("Your Name"); final EditText input = new EditText(this); alert
Edittext
转换为字符串。toString()
方法不起作用,打印时playerName为null。是否有其他方法将edittext转换为字符串
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("Your Name");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
playerName = input.getText().toString();
}
});
alert.show();
如果
playerName
被声明为String
,则不需要强制转换它或任何东西。getText
方法提供了一个CharSequence
,可以用作字符串
问题是您正在“从头开始”创建输入
变量,因此它不会引用任何现有的视图
。你应该这样做:
EditText input = findViewById(R.id.player);
然后你可以:
playerName = input.getText();
下面是如何从编辑文本中获取文本
et = (EditText)findViewById(R.id.resource_id_of_edittext);
String text = et.getText().toString();`
editText.getText().toString()
为您提供一个字符串alertdialog看起来不错,但错误可能位于代码的其余部分。您必须记住,您不能使用var playerName,只能使用对话框的show(),如果您想打印出名称,您应该使用您在此处调用的runnable wich执行此操作:
static Handler handler = new Handler();
[.......]
public void onClick(DialogInterface dialog, int whichButton) {
playerName = input.getText().toString();
handler.post(set_playername);
}
[.......]
static Runnable set_playername = new Runnable(){
@Override
public void run() {
//printout your variable playerName wherever you want
}
};
编辑以澄清:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("Your Name");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
playerName = input.getText().toString();
//call a unction/void which is using the public var playerName
}
});
alert.show();
// the variable playerName is NULL at this point
它应该但是playerName打印null。检查playerName文本字段是否正确初始化并分配给它?我正在尝试将值保存到一个变量,因此如果我在alert.show()之前声明另一个变量来保存它,这会起作用吗?一般的问题是,alert.show()没有暂停调用void或函数的执行者。show()的代码将立即被执行,而不是等待OK。如果要使用该变量,可以将该值存储到公共变量中,但只能在其他空格/函数中使用,而不能在调用空格/函数的对话框中使用(如vb或c#)。如果您想立即使用它,您必须在对话框的onclick方法中调用using函数,有时这必须是可运行的
String mystring=input.getText().toString();