所以我正在制作一个小应用程序,它需要一个逗号分隔的列表并返回该列表中的一个随机单词,但我无法从 EditText
View 中获取文本。
我在 Stackoverflow 上看到您应该使用 EditText.getText().toString()
方法来从 EditText
获取文本。但是,当我使用这些方法时,该应用程序停止工作。我运行了调试器,我的输入变量引用了一个空字符串,并且我还收到一条错误,指出没有本地提交变量。
这是java文件:
public class MainActivity extends AppCompatActivity {
EditText UserInput;
Button reset;
Button Submit;
TextView result;
String Input;
String Result;
String word;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UserInput = (EditText) findViewById(R.id.UserInput);
reset = (Button) findViewById(R.id.Reset);
Submit = (Button) findViewById(R.id.Choose);
result = (TextView) findViewById(R.id.Result);
Input = UserInput.getText().toString();
Result = "Your choice should be:";
Submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random random = new Random();
String[] List = Input.split(",");
int num = random.nextInt(List.length - 1);
word = List[num];
Result = Result + word;
result.setText(Result);
}
});
}
这是 Activity 的 EditText
View :
<EditText
android:id="@+id/UserInput"
android:layout_width="273dp"
android:layout_height="59dp"
android:layout_marginStart="8dp"
android:layout_marginTop="36dp"
android:layout_marginEnd="8dp"
android:ems="10"
android:hint="Choice A, Choice B, Choice C,..."
android:inputType="text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.515"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/Instructions" />
例如,如果我在 EditText
中写入“a,b”,我希望输入为“a,b”,但事实并非如此。当我调试时,它显示它是一个空字符串,我不知道为什么。还。我收到另一个错误,onClick
方法中没有本地提交变量。如何修复这些错误?
最佳答案
在声明时,您正在从 EditText
获取文本,因为 Input
为空。 Input
没有观察编辑文本的内容变化。
为此,您必须在提交之前再次获取输入。
Submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random random = new Random();
Input = UserInput.getText().toString();
if (Input != null) {
String[] List = Input.split(",");
int num = random.nextInt(List.length - 1);
word = List[num];
Result = Result + word;
result.setText(Result);
}
}
});
关于java - 从 EditText 中检索文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53997648/