从Adapterview获取字符串ID

时间:2017-06-17 01:43:05

标签: java android android-adapterview

所以我有以下代码

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String selectedItem = parent.getItemAtPosition(position).toString();
        switch (selectedItem) {
            case "Lowest Price":// handle...
                break;
            case "Price": // handle...
                break;
            default: break;
        }
        adapter.notifyDataSetChanged();
    }

但是我已经在字符串文件中填充了适配器的字符串。

有没有办法从父级或视图中获取id,以便我可以执行以下操作:

switch(id)
case R.resource.my_string

1 个答案:

答案 0 :(得分:0)

如果你在string.xml中使用String数组,那么

<array name="price_type">
    <item>Lowest Price</item>
    <item>Price</item>
</array>

你可以直接从数组中获取值,

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    final String[] priceValues = getResources().getStringArray(R.array.price_type);

    String selectedItem = priceValues[position];

    // if you want to use more manipulation based on the item you can use the position of the value.

    adapter.notifyDataSetChanged();
}