【问题标题】:getResources().getStringArray(R.array.Passing_own_variable);getResources().getStringArray(R.array.Passing_own_variable);
【发布时间】:2017-02-09 11:48:59
【问题描述】:

我在 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

这是类似的东西

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;

【问题讨论】:

  • @Exigente05 我已经在代码中的 cmets 中说过。标题本身就是问题。我们如何在 R.array 中传递 own_variable?

标签: android arrays string listview


【解决方案1】:

首先获取该数组的 id,

假设我们正在使用“车辆”数组

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

那就用这个id

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

【讨论】:

  • 是的,工作!!我得到了我想要的!!非常感谢 Exigente05,你是完美的!
猜你喜欢
  • 1970-01-01
  • 2019-12-13
  • 1970-01-01
  • 2020-06-22
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
  • 2019-07-30
相关资源
最近更新 更多