[英]Android Studio- Display one string if a button is pressed with no text in the textbox and another when text is inputted
I am incredibly new to Android Studio and was hoping to get some assistance.我对 Android Studio 非常陌生,希望能得到一些帮助。 For some reason, this code is only displaying the ("Hi, " +name) portion.
出于某种原因,此代码仅显示 ("Hi, " +name) 部分。 I am not sure what I am doing wrong or how to get the ("You must enter a name") portion to show when there is no text that has been inputted.
我不确定我做错了什么或如何在没有输入文本时显示(“您必须输入姓名”)部分。 We are needing to incorporate a SayHello() function into this and I am not sure if I am doing it properly... enter image description here
我们需要将 SayHello() function 合并到其中,我不确定我是否做得正确...在此处输入图像描述
package com.example.assignment5_2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText nameText;
TextView textGreeting;
Button buttonSayHello;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameText = (EditText) findViewById(R.id.nameText);
textGreeting = (TextView) findViewById(R.id.textGreeting);
buttonSayHello = (Button) findViewById(R.id.buttonSayHello);
buttonSayHello.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SayHello();
}
public void SayHello() {
String name = nameText.getText().toString();
if (name != null) {
textGreeting.setText("Hi, " + name);
} else {
textGreeting.setText("You must enter a name");
buttonSayHello.setEnabled(name.isEmpty());
}
}
});
}
}
Hey I've tried your code and I guess I found the issue, please alter your condition as follows:嘿,我已经尝试了您的代码,我想我发现了问题,请按如下方式更改您的条件:
public void SayHello() {
String name = nameText.getText().toString();
if (!name.isEmpty()) {
textGreeting.setText("Hi, " + name);
} else {
textGreeting.setText("You must enter a name");
}
It is preferred to use .isEmpty()
method to check if the string is empty or not instead of using,= null or == null, by altering your condition like I mentioned above your empty EditText
check will work too.最好使用
.isEmpty()
方法来检查字符串是否为空,而不是使用,= null 或 == null,通过像我上面提到的那样更改您的条件,您的空EditText
检查也将起作用。 Check screenshots below for both cases:检查以下两种情况的屏幕截图:
try this and do let me know if it works !!试试这个,让我知道它是否有效!
I think I got your problem, in the SayHello
you have to change if(name != null)
to我想我遇到了您的问题,在
SayHello
中您必须将if(name != null)
更改为
if(.name.trim().equals(""))
or if(name.trim().length > 0
if(.name.trim().equals(""))
或if(name.trim().length > 0
Hope this helps希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.