I'm new with Android and want to understand another one moment. I've got a strings.xml, which values I use in activity.xml. How use this values from JAva code in switch block?
private void gotoActivity(CharSequence text) {
switch (text.toString()) {
case getString(R.string.title_activity_first):
break;
case RADIO_BUTTON_SECCOND:
break;
}
}
Not compiles 'cos of "Constant expression required". But the main benefit of strings.xml - is string constants in one place.
Help plz.
Unfortunately you cannot use resource string in switch-case. You have two options. Choose anyone...
use static final String in your activity.
Example: Initialize the strings
public static final String TITLE_ACTIVITY_FIRST = "activity_title";
public static final String RADIO_BUTTON_SECCOND = "radio_button_second";
Then you can use the TITLE_ACTIVITY_FIRST in switch case. like,
switch(text.toString()){
case TITLE_ACTIVITY_FIRST: break;
case RADIO_BUTTON_SECOND: break;
}
No error will show!
use if-else. You can then use your resource strings.
Example:
if(text.toString().equals(getString(R.string.title_activity_first))){
//your code in case of 1st condition
}else if(text.toString().equals(getString(R.string.title_activity_second))){
//your code in case of 2nd condition
}
The second might look clumsy. But you wont have to change your code too much. Whereas the first one might look quite handy and you can easily modify later. Hope it helps!
You can not use getString(R.string.title_activity_first) since it returns a localised string from the application's package's default string table.So the result will be different based on the locale and hence it won't be a constant.You can not even get a particular local string using getString() method.Better to use a static final String filed instead.Please refer here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With