0

我是 android 开发的菜鸟,我想知道是否有一种有效的方法可以从字符串和数组资源中设置值。当用户从很长的列表视图中选择一个值时,我必须访问大量的字符串和 arrya 资源。例如,如果列表视图包含 Acne、Bruise 等,是否可以这样设置值:

 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    switch(arg0.getId()){
    case R.id.ailmentslistview:

        String value = ((TextView) arg1).getText();

        remedyDescription.setText(R.string.value_description);
        remedyCause.setText(R.string.value_cause);
        remedyHerbs.setText(R.string.value_herbs);
        remedyFoods.setText(R.string.value_foods);
        remedyListSupplements = res.getStringArray(R.array.value_supplements);
        remedyListDosage = res.getStringArray(R.array.value_dosage);
        remedyListComments = res.getStringArray(R.array.value_comment);

        break
        }
     } 

代替:

 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub
    switch(arg0.getId()){
    case R.id.ailmentslistview:

            if(String value = ((TextView) arg1).getText()==Acne){

        remedyDescription.setText(R.string.acne_description);
        remedyCause.setText(R.string.acne_cause);
        remedyHerbs.setText(R.string.acne_herbs);
        remedyFoods.setText(R.string.acne_foods);
        remedyListDosage = res.getStringArray(R.array.acne_dosage);
        remedyListComments = res.getStringArray(R.array.acne_comment);

            }else if(String value = ((TextView) arg1).getText()==Bruise) {

        remedyDescription.setText(R.string.bruise_description);
        remedyCause.setText(R.string.bruise_cause);
        remedyHerbs.setText(R.string.bruise_herbs);
        remedyFoods.setText(R.string.bruise_foods);
        remedyListDosage = res.getStringArray(R.array.bruise_dosage);
        remedyListComments = res.getStringArray(R.array.bruise_comment);

            }


                break;
            }
  }

非常感谢任何见解。

4

3 回答 3

1

您可以使用getIdentifier (String name, String defType, String defPackage) 进行动态资源加载。

context.getResources().getIdentifier(name, "string", context.getApplicationInfo().packageName);

在您的情况下,您可以通过以下方式创建字符串名称,

字符串值 = ((TextView) arg1).getText();

名称 = value.toLowerCase() + "_description";

所以..

于 2013-05-26T18:42:52.083 回答
1
String myString    = getApplicationContext().getResources().getString(R.string.myString);
String []  myArray = getApplicationContext().getResources().getStringArray(R.array.myArray);

了解更多信息。

于 2013-05-26T17:21:00.093 回答
1

String myString = getApplicationContext().getResources().getString(R.string.myString); String [] myArray = getApplicationContext().getResources().getStringArray(R.array.myArray);

于 2014-04-30T10:50:02.813 回答