简体   繁体   English

如何将 TextView 中的文本与字符串值进行比较

[英]How to compare text in TextView with String value

This question has been asked severally and I collected all the answers and tried them but it is not really working for me.这个问题已被多次提出,我收集了所有答案并尝试了它们,但它对我来说并不真正有效。 I have a TextView which displays one of these names at a time: Joseph99, Thomas79, Marry29, Matthew21我有一个 TextView 一次显示以下名称之一: Joseph99、Thomas79、Marry29、Matthew21

Below this TextView I have a button.在这个 TextView 下面我有一个按钮。 What I want is this, When TextView displays for example this name: Joseph99, i want the button to change its text to: Yes我想要的是这个,当 TextView 显示这个名字时:Joseph99,我希望按钮将其文本更改为:是

If any other name is displayed on the TextView I want the button to say: NO.如果 TextView 上显示任何其他名称,我希望按钮说:否。 For now the button actually does nothing I just want it to change text to either YES or NO depends on what is displayed on a TextView.现在这个按钮实际上什么都不做,我只是想让它改变文本为 YES 或 NO 取决于 TextView 上显示的内容。

I have tried the following in the onCreate();我在onCreate();中尝试了以下内容

final textview = tv.getText().toString();
final String str1 = "Joseph99";
final String str2 = "Thomas79"
final String str3 = "Marry29"
final String str4 = "Matthew21"

if(str1.matches(textview)){
button.setText("YES");
}else{button.setText("NO");}

On the above code the text matches but I am getting a NO on a button even if the text on TextView is equal to str1.在上面的代码中,文本匹配,但即使 TextView 上的文本等于 str1,我也得到一个按钮上的 NO。 I also tried.equals like below:我也试过.equals,如下所示:

if(str1.equals(textview)){
button.setText("YES");
}else{button.setText("NO");}

But I still get the NO even if the TextView has same text with str1.但即使 TextView 与 str1 具有相同的文本,我仍然得到否定。

I also tried this code:我也试过这段代码:

if(!textview.getText().toString().matches("Joseph99");

And also this:还有这个:

if(!textview.getText().toString().equals("Joseph99")

But the button text does not change, it is always NO, whether the TextView displays Joseph99 or not.但是按钮文字没有变化, TextView是否显示Joseph99总是NO。

Note: The data which shows on TextView comes from SharedPreferences and it changes time by time.注意:TextView 上显示的数据来自SharedPreferences ,并且会随时间变化。

There might be an error on my code but its three days now trying to figure out, but I have failed我的代码可能有一个错误,但它现在试图弄清楚三天,但我失败了

Well I will highly recommend you to debug and see as everything seems correct but I think it's the issue with white-spaces好吧,我强烈建议您调试并查看一切似乎正确,但我认为这是空格的问题

Try this尝试这个

 if(str1.equals(textview.trim())){button.setText("YES");}else{button.setText("NO");}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM