Java/Android 编程 / EditText -> getText().toString()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14265553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java/Android Programming / EditText -> getText().toString()
提问by subarachnid
Possible Duplicate:
How do I compare strings in Java?
why equals() method when we have == operator?
All I'm trying to do here is to compare a text that was entered in a text-field widget with a given string ("abc") and then set the button-text to either "wrong pass" or "pass ok". However, the button-text is always set to "wrong pass" even if I enter the correct "password". What am I doing wrong?
我在这里要做的就是将在文本字段小部件中输入的文本与给定的字符串(“abc”)进行比较,然后将按钮文本设置为“错误通过”或“通过正常”。但是,即使我输入了正确的“密码”,按钮文本也始终设置为“错误通过”。我究竟做错了什么?
public class FullscreenActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
final Button button = (Button) findViewById(R.id.button);
final EditText textedit = (EditText) findViewById(R.id.textedit);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (textedit.getText().toString() == "abc")
button.setText("pass ok"); // doesn't work
else
button.setText("wrong pass");
}
});
}
...
回答by kosa
one issue is:
一个问题是:
if (textedit.getText().toString() == "abc")
should be
应该
if (textedit.getText().toString().equals("abc") )
even better:
甚至更好:
if ("abc".equals(textedit.getText().toString()))
It is always better to use equals()
while comparing String/Objects instead of using ==
equals()
在比较字符串/对象时使用总是更好,而不是使用==
==
checks for reference equality. equals()
check for content equality.
==
检查引用相等性。equals()
检查内容是否相等。
回答by Sam
You cannot compare String in Java / Android with ==
, you must use equals()
:
您不能将 Java/Android 中的 String 与 进行比较==
,您必须使用equals()
:
if (textedit.getText().toString().equals("abc"))
You can find a good explanation of whyin: How do I compare strings in Java?
您可以在以下文章中找到对原因的很好解释:如何比较 Java 中的字符串?
回答by Marcos Aguayo
Try this, using "equals".
试试这个,使用“equals”。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText getpass = (EditText)findViewById(R.id.textedit);
String pass = getpass.getText().toString();
if(pass.equals("abc")){
Toast toast = Toast.makeText(getApplicationContext(), "pass ok", Toast.LENGTH_SHORT);
toast.show();
}else{
Toast toast = Toast.makeText(getApplicationContext(), "wrong pass", Toast.LENGTH_SHORT);
toast.show();
}
}
});
}