简体   繁体   English

用.equals()比较两个字符串不起作用

[英]compare two strings with .equals() don't work

I get a string form a list and try to compare it with some strings in the values and then do some stuff 我从列表中得到一个字符串,并尝试将其与值中的一些字符串进行比较,然后执行一些操作

for(int i=0; i<sizeOfList; i++){

    String LIST_TITLE;

    LIST_TITLE = list_title.get(i); //the List list_title includes some strings

    if(LIST_TITLE.equals(R.string.percentbattery)) {
        //do stuff
        Log.d("EQUAL!","" + LIST_TITLE);
    } else if(LIST_TITLE.equals(R.string.screenrecorder) == true) {
        //do stuff
        Log.d("EQUAL!","" + LIST_TITLE);
    } else if(LIST_TITLE.equals(R.string.eightsms) == true) {
        //do stuff
        Log.d("EQUAL!","" + LIST_TITLE);
    } else {
        // do stuff
        Log.e("TITLE NOT EQUAL","" + LIST_TITLE);
    }
}

If I compare my LIST_TITLE with the (R.string. ...) in my Logcat they are equal, but I get only the "TITLE NOT EQUAL" Log from the else statement. 如果将我的LIST_TITLE与Logcat中的(R.string。...)进行比较,则它们相等,但是从else语句中只能得到“ TITLE NOT EQUAL”日志。

Is there another way to compare these strings? 还有另一种比较这些字符串的方法吗? the "==" method also don't work. “ ==”方法也不起作用。

R.string.percentbattery is not a String, it's an Integer that is the ID to reference the string. R.string.percentbattery不是字符串,而是一个整数,它是引用字符串的ID。

what u want is: 你想要的是:

LIST_TITLE.equals(context.getResources.getString(R.string.percentbattery))
LIST_TITLE.equals(R.string.percentbattery)

这是不正确的,因为您要尝试将字符串与资源ID进行比较,您应该首先从资源中获取字符串:

LIST_TITLE.equals(getResources().getString(R.string.percentbattery))

R.string.xxx is an int . R.string.xxx是一个int You need to get the String from that res 您需要从该res获取String

Something like 就像是

if(LIST_TITLE.equals(getResources().getString(R.string.percentbattery)))

This is assuming you have Activity Context available. 这是假设您有Activity Context可用。 Otherwise, you would need to add a Context variable in front of getResources() 否则,您将需要在getResources()前面添加一个Context变量。

R.string.some_id is just an integer by which you can get the String from the resources. R.string.some_id只是一个整数,您可以通过该整数从资源中获取String。 So in order to compare Strings correctly in you case you have to do: 因此,为了正确比较Strings ,您必须执行以下操作:

String precentBattery = getResources().getString(R.string.percentbattery);
if (LIST_TITLE.equals (percentBattery)) ...

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

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