简体   繁体   中英

Comparing a String to String extract in android

I am obtaining the title of a Context Menu Item then comparing it to a string. The code below does not seem to work as expected, why?

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle().equals(String.valueOf(R.string.item_edit_text))){ // <-- compared to string extract
        Toast.makeText(this, "Match",Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "No Match",Toast.LENGTH_SHORT).show();
    }
    return super.onContextItemSelected(item);
}

The item.getTitle results in "Edit" and R.string.item_edit_text is "Edit". So why the above code results in "No Match"?

The code below seems to work fine, however,

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle().equals("Edit")){ // <--- Compared to hardcoded string
        Toast.makeText(this, "Match",Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "No Match",Toast.LENGTH_SHORT).show();
    }
    return super.onContextItemSelected(item);
}

R.string.item_edit_text is probably of EditText type.

When you write :

String.valueOf(R.string.item_edit_text)

it returns finally R.string.item_edit_text.toString() but R.string.item_edit_text.toString() doesn't return the text of the EditText .

You should rather do R.string.item_edit_text.getText().toString() to apply tge toString() on the Editable instance returned by getText() .

You could so write it :

if (item.getTitle().equals(R.string.item_edit_text.getText().toString())){ 

Or:

if (item.getTitle().equals(getString(R.string.item_edit_text))){

This is what i found and it seems explaining.

The getString(int) method in Context and its subclasses (like Activity) are meant specifically to look up a string resource that was included in your app, and it takes a string resource id as a parameter to know which resource to find. Again, in Java this parameter appears to be just a normal integer.

String.valueOf(int) is entirely different. It is a Java library function that takes an integer and produces a String representation of that integer, eg String.valueOf(5) returns "5". It is not useful for getting Android string resources.

String.valueOf() Returns the string representation of the int argument that you pass into it. And you have passed an Resource id to the method. So the method will that method will return the String representation not the resource as you expected. You should use getString(R.string.item_edit_text) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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