【问题标题】:How to get items from a string-array using an ID-based mechanism?如何使用基于 ID 的机制从字符串数组中获取项目?
【发布时间】:2015-06-19 15:22:13
【问题描述】:

问题很简单。我已经在 Android 中实现了一个导航抽屉。现在,我有一个菜单,其中每个项目都是 string-array 中的 strings.xml 中的一个项目。每次用户单击其中一个菜单项时,都会创建一个片段。在片段类中,我想在项目中switch 以便用适当的信息填充主要内容。我知道的唯一方法是检查项目的位置,但是如果将来我要添加更多项目会怎样?我需要更改代码中的所有位置值。

所以,我想知道是否有一种方法可以为每个元素分配一种 ID。我已经阅读here 为它们中的每一个定义一个单独的字符串,但是我如何检查这些值?我尝试了以下方式,但它给了我一个Constant expression required 错误:

Resources resources = getResources();
    switch(item_string) {
        case resources.getString(R.string.item1):
            //TODO
        case resources.getString(R.string.item2):
            //TODO
        ...

【问题讨论】:

  • 对于字符串数组,您应该使用索引。对于单独的字符串,您可以使用反射。对于数据库表...我假设您知道如何管理它。
  • 哦,来吧...在 raw/assets 中使用 data.json ...它会为您省去很多麻烦...您需要简单的数组:使用字符串数组...您需要一些结构化数据使用:xml/json/database
  • 也许你可以为每个项目设置标签(来自抽屉列表适配器的 getTag 方法)并在这里使用它。
  • 或者定义另一个与现有数组长度相同的数组,并在这个新数组中定义所有 id。使用现有数组中的导航项位置从这个新数组中获取 id 值。确保这两个数组保持同步。
  • @Selvin:你能说得更准确点吗?

标签: android arrays xml string android-fragments


【解决方案1】:

按照 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:
        [...]

[...]

希望我的例子可以帮助其他人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    相关资源
    最近更新 更多