![](/img/trans.png)
[英]Android Studio- Click button to change the buttons text multiple times
[英]Android Studio- Display one string if a button is pressed with no text in the textbox and another when text is inputted
我對 Android Studio 非常陌生,希望能得到一些幫助。 出於某種原因,此代碼僅顯示 ("Hi, " +name) 部分。 我不確定我做錯了什么或如何在沒有輸入文本時顯示(“您必須輸入姓名”)部分。 我們需要將 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());
}
}
});
}
}
嘿,我已經嘗試了您的代碼,我想我發現了問題,請按如下方式更改您的條件:
public void SayHello() {
String name = nameText.getText().toString();
if (!name.isEmpty()) {
textGreeting.setText("Hi, " + name);
} else {
textGreeting.setText("You must enter a name");
}
最好使用.isEmpty()
方法來檢查字符串是否為空,而不是使用,= null 或 == null,通過像我上面提到的那樣更改您的條件,您的空EditText
檢查也將起作用。 檢查以下兩種情況的屏幕截圖:
試試這個,讓我知道它是否有效!
我想我遇到了您的問題,在SayHello
中您必須將if(name != null)
更改為
if(.name.trim().equals(""))
或if(name.trim().length > 0
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.