[英]How to get data from multiple editText and show in textView if one or more is empty in Android Studio?
In my app there are two EditText named name
and age
, a TextView named showData
and a Button.在我的应用程序中有两个名为
name
和age
的 EditText,一个名为showData
的 TextView 和一个 Button。 Basically what I want to do is when a user enters the data in the EditText and clicks the Button the TextView will show the output like this基本上我想要做的是当用户在 EditText 中输入数据并单击按钮时,TextView 将像这样显示 output
My name is
name
我的名字是
name
I'mage
years old我今年
age
So for doing this I used If Else
inside a setOnClickListener
and wrote the code like this,所以为了做到这一点,我在
setOnClickListener
中使用了If Else
并编写了这样的代码,
if (name.isEmpty() && age.isEmpty()) {
showData.setText(null);
}
else if (age.isEmpty()) {
showData.setText("My name is " + name);
}
else if (name.isEmpty()) {
showData.setText("I'm " + age + " years old");
}
else{
showData.setText("My name is " + name +
"\n I'm " + age + " years old");
}
I'm a beginner in both Java and Android Studio so confused about things there.我是 Java 和 Android Studio 的初学者,所以对那里的事情感到困惑。 It would be great if you tell me how to make the app work in standard programming with fewer codes.
如果您能告诉我如何使用更少的代码使该应用程序在标准编程中运行,那就太好了。 I mean if and editText is empty the textView won't show any data related to it.
我的意思是,如果 editText 为空,textView 将不会显示任何与之相关的数据。
EG: If the user inputs only the name textView will show My name is name
only.例:如果用户只输入姓名 textView 将显示My name is
name
only。 Or if the user inputs only the age textView will show I'm age
years old only.或者,如果用户仅输入年龄 textView 将仅显示我的
age
。 Or if user gives both the textView will show both或者如果用户同时提供 textView 将显示两者
Probably this would be appropriate solution in Java (hopefully I did not code a typo, as I am typing directly in the SO pane):这可能是 Java 中的适当解决方案(希望我没有编写错字,因为我直接在 SO 窗格中键入):
StringBuilder sb = new StringBuilder();
if (!age.isEmpty()) {
sb.append("My name is " + name);
}
if (!name.isEmpty()) {
if (sb.length() != 0) {
sb.append("\n");
}
sb.append("I'm " + age + " years old");
}
showData.setText(sb.toString());
By the way, if you were using Kotlin this would have been sooo much nicer.顺便说一下,如果您使用的是 Kotlin,那就更好了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.