如何将 switch case 场景与字符串资源而不是硬编码名称一起使用?我的字符串与用于拼写的名称完全相同。
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MainListAdapter adapter = (MainListAdapter) parent.getAdapter();
Main continent = adapter.getItem(position);
if (mTwoPane) {
View rowView = view;
setItemSelected(continent, rowView);
Fragment newFragment;
switch (stringRes) {
case R.id.africa:
newFragment = new FragmentAfrica();
break;
case R.id.asia:
newFragment = new FragmentAsia();
break;
case R.id.europe:
newFragment = new FragmentEurope();
break;
default:
newFragment = new FragmentAfrica();
}
MainActivity activity = (MainActivity) view.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detail_container, newFragment);
transaction.commit();
} else {
}
最佳答案
开关标签(即 case "africa":
中的 "africa"
)必须是 constant expressions根据 JLS § 14.12 .因此,如果您想使用 switch
,您必须将字符串资源值存储在一个常量变量中,然后将该常量用作开关标签。
示例(使用类常量或局部常量):
class Example {
public static final String CONTINENT_EUROPE =
getResources().getString(R.string.europe); // Option 1: class constants
public static final String CONTINENT_NORTHERN_AMERICA =
getResources().getString(R.string.northernAmerica);
public void foo() {
final String continentAfrica =
getResources().getString(R.string.africa); // Option 2: local constants
final String continentAsia =
getResources().getString(R.string.asia);
switch (continent) {
// Option 1:
case continentAfrica:
newFragment = new FragmentAfrica();
break;
case continentAsia:
newFragment = new FragmentAsia();
break;
// Option 2:
case CONTINENT_EUROPE:
newFragment = new FragmentEurope();
break;
case CONTINENT_NORTHERN_AMERICA:
newFragment = new FragmentNorthernAmerica();
break;
// ...
}
}
关于java - 如何将 switch case 与字符串资源一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31756149/