我有兩個活動。首先,我把一個ListView
的項目列表。第二,我也想列出一些項目,但其內容將取決於在第一個Activitу
中按下的元素的位置。這是第一個ListView
活動的代碼:如何將數字賦給數組並將其顯示在列表視圖中?
public class ListView1 extends Activity implements OnClickListener {
private ListView lv1;
private String cats[];
//some code
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
Bundle bundle = getIntent().getExtras();
final String category = bundle.getString("category");
lv1 = (ListView) findViewById(R.id.listView);
ArrayAdapter<CharSequence> adapter = ArrayAdapter
.createFromResource(this, R.array.first_list,
R.layout.list_items);
lv1.setAdapter(adapter);
cats = getResources().getStringArray(R.array.first_list);
lv1.setTextFilterEnabled(true);
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
String defStrID = new Integer(position).toString();
Intent intent = new Intent();
intent.setClass(ListView1.this, ListView2.class);
Bundle b = new Bundle();
b.putString("defStrID", defStrID);
intent.putExtras(b);
startActivity(intent);
}
});
}
}
這是獲取列表中的元素的位置的代碼:
String defStrID = new Integer(position).toString();
我得到它在第二ListView
有:
Bundle bundle = getIntent().getExtras();
String elementID = bundle.getString("defStrID");
我在arrays.xml
第ListView
有一些陣列。例如:
R.array.category1
R.array.category2
R.array.category3
R.array.category4
或數組這樣的(這不是很重要):
String category1[] = { //some items here }
String category2[] = { //some items here }
etc.
舉個例子,只有幾個陣列,其實更多,所以我不希望使用if else
建設。如何以另一種方式做到這一點,我不知道。第二個ListView
活動將與第一個相同,除了上述內容。
次活動:
public class List2 extends ListActivity {
private ListView lv1;
private String category1[] = {"Name1", "Name2"};
private String category2[] = {"Surname1", "Surname2"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
;
String elementID = bundle.getString("defStrID");
String arrayName = "category" + elementID;
int id = getResources().getIdentifier(arrayName, "array",
this.getPackageName());
Log.v("LOOK_FOR_ME", "category" + " and the id i got is " + id);
String[] stats = getResources().getStringArray(id);
lv1.setAdapter(new ArrayAdapter<String>(this, R.layout.list_items,
stats));
}
}
在第二個actitivy你想要的數組從xml> – 2012-03-01 19:44:10
@Samir根據在第一個活動中擊中的元素的位置,我想放入第二個活動適當的數組。例如:如果我在第一個活動中按下第一個元素,我將在第二個活動中獲得list1中的category1的數組,等等。 – Sabre 2012-03-01 19:47:51
您在第一個活動中獲得的位置是基於零的。值將是R.array.category0,R.array.category1,... – njzk2 2012-03-02 10:55:06