如何在每个循环中更改数组名称?
这是我的代码的简化版本:
if (POSITION1 == 1) {
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(Main2Activity.this,
R.layout.simple_list_item_single_choice_2,
getResources().getStringArray(R.array.Électron_P));
listView.setAdapter(mAdapter);
}
if (POSITION1 == 2) {
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(Main2Activity.this,
R.layout.simple_list_item_single_choice_2,
getResources().getStringArray(R.array.Monstre_P));
listView.setAdapter(mAdapter);
}
if (POSITION1 == 3) {
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(Main2Activity.this,
R.layout.simple_list_item_single_choice_2,
getResources().getStringArray(R.array.Neutron_P));
listView.setAdapter(mAdapter);
}
我想让它在单个循环中工作,但我不明白需要替换数组的名称
for (i = 0; i <= 3; i++) {
if (POSITION1 == i) {
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(Main2Activity.this,
R.layout.simple_list_item_single_choice_2,
getResources().getStringArray(R.array.??????));
listView.setAdapter(mAdapter);
}
}
任何帮助将不胜感激!
答案 0 :(得分:3)
我不理解您问题的循环部分,但您可以使用字典存储POSITION1
的有效值
int[] options= new int[] {
R.array.Électron_P,
R.array.Monstre_P,
R.array.Neutron_P
};
int resId = options[POSITION1 - 1];
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(Main2Activity.this,
R.layout.simple_list_item_single_choice_2,
getResources().getStringArray(resId));
listView.setAdapter(mAdapter);
答案 1 :(得分:2)
你不能使用循环,试试这个:
HashMap positions = new LinkedHashMap();
positions.put(1,R.array.Électron_P);
positions.put(2,R.array.Monstre_P);
positions.put(3,R.array.Neutron_P);
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(Main2Activity.this,
R.layout.simple_list_item_single_choice_2,
getResources().getStringArray(positions.get(POSITION1)));
listView.setAdapter(mAdapter);
答案 2 :(得分:0)
尝试使用开关简化
int selectedArray = 0;
switch(POSITION1) {
case 1:
selectedArray = R.array.Électron_P;
break;
case 2:
selectedArray = R.array.Monstre_P;
break;
case 3:
selectedArray = R.array.Neutron_P;
break;
}
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(Main2Activity.this,
R.layout.simple_list_item_single_choice_2,
getResources().getStringArray(selectedArray));
listView.setAdapter(mAdapter);