正如Selvin建議,我在assets/
創造了一個JSON文件中的JSON數組中的每個元素對應於包括菜單項三個字段(ID,名稱和圖標),例如:
[
{"id": 1, "name": "item1", "icon": "icon1"},
{"id": 2, "name": "item2", "icon": "icon2"},
{"id": 3, "name": "item3", "icon": "icon3"},
{"id": 4, "name": "item4", "icon": "icon4"}
]
然後,我首先創建了一個Item
類映射JSON對象:
public class Item {
private int id;
private String name;
private String icon;
public Item(JSONObject object) {
try {
this.id = object.getInt("id");
this.name = object.getString("name");
this.icon = object.getString("icon");
} catch (JSONException e) {
e.printStackTrace();
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
// Factory method to convert an array of JSON objects into a list of objects
// User.fromJson(jsonArray);
public static ArrayList<Item> fromJson(JSONArray jsonObjects) {
ArrayList<Item> items = new ArrayList<Item>();
for (int i = 0; i < jsonObjects.length(); i++) {
try {
items.add(new Item(jsonObjects.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return items;
}
}
和相應的適配器:
public class ItemAdapter extends ArrayAdapter<Item> {
public ItemAdapter(Context context, ArrayList<Item> items) {
super(context, 0, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Item item = getItem(position);
int item_id = item.getId();
String item_name = item.getName();
int item_icon_id = parent.getContext().getResources().getIdentifier(item.getIcon(),
"drawable", parent.getContext().getPackageName());
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.drawer_list_item, parent, false);
}
// Lookup view for data population
ImageView item_icon_view = (ImageView) convertView.findViewById(R.id.item_icon);
TextView item_name_view = (TextView) convertView.findViewById(R.id.item_name);
// Populate the data into the template view using the data object
item_name_view.setText(item_name);
item_icon_view.setImageResource(item_icon_id);
// Return the completed view to render on screen
return convertView;
}
}
最後,在我的活動我通過所選擇的項目的ID:
Fragment fragment = new MainFragment();
Bundle args = new Bundle();
args.putInt(MainFragment.ARG_ITEM_ID, item.getId());
args.putString(MainFragment.ARG_ITEM_NAME, item.getName());
fragment.setArguments(args);
和我在我的片段在下面的切換爲:
int item_id = getArguments().getInt(ARG_ITEM_ID);
switch(item_id) {
case 1:
[...]
case 2:
[...]
[...]
希望我的榜樣能幫助別人。
對於字符串數組,您應該使用索引。對於單獨的字符串,您可以使用反射。對於數據庫表...我假設你知道如何管理它。 –
哦來吧......在raw/assets中使用data.json ......它將爲您節省很多麻煩......您需要簡單的數組:使用字符串數組......您需要一些結構化的數據使用:xml/json/database – Selvin
也許你可以爲每個項目設置標籤(來自抽屜適配器的getTag方法)並在這裏使用它。 – km86