。getResources()getStringArray(R.array.Passing_own_variable);

时间:2017-02-09 11:48:59

标签: android arrays string listview

我在listView上打印一些字符串数据,我从strings.xml中获取字符串数组中的数组。为了让你更清楚,我举了一个例子:

的strings.xml

<string-array name="vehicle">
<item>car</item>
<item>bur</item>
<item>van</item>
</string-array>

<string-array name="food">
<item>cake</item>
<item>donuts</item>
<item>Ice-cream</item>
</string-array>

<string-array name="fruits">
<item>apple</item>
<item>banana</item>
<item>grapes</item>
</string-array>


 Now, Something In NavigationItem like:

 vehicle
 food
 fruits

然后,当我选择车辆时,我会开始像下面这样的远程和

  case R.id.vehicle:
                bundle.putString("key_variable","vehicle");
                msgListActivtiy loveweb=new msgListActivtiy();
                loveweb.setArguments(bundle);
                fragmentTransaction=fragmentManager.beginTransaction().replace(R.id.mainContainer,loveweb);
                fragmentTransaction.commit();
                break;

   case R.id.foods:
                bundle.putString("key_variable","food");
                //othercodes
                break;

case R.id.fruits:
               bundle.putString("key_variable","fruits");
               //othercodes
               break;

现在,这将打开一个msgListActivity

这里有Likethis的东西

public class msgListActivtiy extends Fragment {
String localUrl;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Bundle bundle=this.getArguments();
    localUrl=bundle.getString("key_variable","defaultvalue");
    View rootView=inflater.inflate(R.layout.lv,container,false);
    ListView listView= (ListView) rootView.findViewById(R.id.listview);
  //Now, below instead of giving car I need to set the localvariable that I 
//have declared above.
  //Something I want to pass like
//String[] res="getActivity().getResources().getStringArray(R.array."+localvariable+");"; I tried this and give me error like found string instead of String[]
//how can we achieve that? If that can't be done then how do we handle these kinds of situations??
    String[] res=getActivity().getResources().getStringArray(R.array.need_variable_from_bundle_above);
    ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,res);
    listView.setAdapter(adapter);
    return rootView;

1 个答案:

答案 0 :(得分:1)

首先获取该数组的ID,

假设我们正在使用“车辆”阵列

int resId = getResources().getIdentifier("vehicle", "array", getActivity().getPackageName());

然后使用此ID

String[] res = getResources().getStringArray(resId);