gpt4 book ai didi

java - 从 EditText 中检索文本

转载 作者:太空狗 更新时间:2023-10-29 16:25:56 26 4
gpt4 key购买 nike

所以我正在制作一个小应用程序,它采用逗号分隔列表并返回该列表中的随机单词,但我无法从 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 未观察 edittext 的内容变化。

为此,您必须在提交之前再次获取输入。

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com