我的 setText 代码有什么问题?
What is wrong with my setText code?
这段代码的目的很简单,当你打开应用程序时,默认文本是 "hello word" 然后你点击按钮更改为 "app name" 所以当你再次点击它应该返回到 "hello word" 但第二次单击时没有任何反应。
TextView myText;
String appName;
String helloWord;
String txt;
myText = findViewById (R.id.mytext);
appName = getResources().getString(R.string.app_name);
helloWord = getResources().getString(R.string.helloWord);
txt = myText.getText().toString();
public void changeText(View v){
if (txt.equals(helloWord)){
myText.setText(appName);
}else if(txt.equals(appName)){
myText.setText(helloWord);
}
}
您没有将 TextView
的文本与更改的文本进行比较。
变量 txt
总是 "hello world"
因为它只在第一次赋值。
我是你的 changeText()
方法,你应该重新分配 txt
。
public void changeText(View v){
txt = myText.getText().toString();
if (txt.equals(helloWord)){
myText.setText(appName);
}else if(txt.equals(appName)){
myText.setText(helloWord);
}
}
这段代码的目的很简单,当你打开应用程序时,默认文本是 "hello word" 然后你点击按钮更改为 "app name" 所以当你再次点击它应该返回到 "hello word" 但第二次单击时没有任何反应。
TextView myText;
String appName;
String helloWord;
String txt;
myText = findViewById (R.id.mytext);
appName = getResources().getString(R.string.app_name);
helloWord = getResources().getString(R.string.helloWord);
txt = myText.getText().toString();
public void changeText(View v){
if (txt.equals(helloWord)){
myText.setText(appName);
}else if(txt.equals(appName)){
myText.setText(helloWord);
}
}
您没有将 TextView
的文本与更改的文本进行比较。
变量 txt
总是 "hello world"
因为它只在第一次赋值。
我是你的 changeText()
方法,你应该重新分配 txt
。
public void changeText(View v){
txt = myText.getText().toString();
if (txt.equals(helloWord)){
myText.setText(appName);
}else if(txt.equals(appName)){
myText.setText(helloWord);
}
}