Reputation: 23
I have this array:
<string-array name="menu_array">
<item name="home" >Home</item>
<item name="new" >New</item>
<item name="history" >History</item>
<item id="categories" >Categories</item>
<item id="store" >Store</item>
<item id="configs" >Configurations</item>
And I have this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerLayout.closeDrawer(mDrawerList);
Toast.makeText(SlideMenuActivity.this, "selecionado: " +
switch (position) {
case 0:
break;...
What I want: I want to be able to use the id or name of the clicked item instead of the position. But why? because everytime I change the order of the itens on the array, I also have to change the switch-case. I can't use the value of the item (Home, New,...), because it also change according to language.
<string-array name="menu_array">
<item name="home" >Home</item>
<item name="new" >Novo</item>
<item name="history" >Historico</item>
<item id="categories" >Categorias</item>
<item id="store" >Loja</item>
<item id="configs" >Configuracoes</item>
Any help?
Upvotes: 2
Views: 490
Reputation: 157467
one solution could make use of a JSONObject. E.g.
<string-array name="menu_array">
<item name="home">{"id": 1, "name": "Home"}</item>
<item name="new" >{"id": 2, "name": "New"}</item>
<item name="history" >{"id": 3, "name": "History"}</item>
....
</string-array>
Then you have to retrieve it, parse the JSON, and use a small object to wrap the information:
public static class Info {
public int id;
public String name;
@Override
public String toString() {
return name;
}
}
String[] array = getResources().getStringArray(R.array.menu_array);
ArrayList<Info> dataset = new ArrayList<>();
for (String s : array) {
JSONObject jObj = new JSONObject(s);
Info info = new Info();
info.id = jObj.optInt("id");
info.name = jObj.optInt("name");
dataset.add(info);
}
Then you will have to change your adapter to deal with instance of Info. When you press on an item, in your onItemClick, you can easily retrieve the item at position with
Info info = (Info) parent.getItemAtPosition(position);
and then you can switch
on info.id
Upvotes: 2
Reputation: 1170
if you are extending Adapter class in getView method you can set tag for every view which is being created and view parameter in onItemClick method returns the same view and you can getTag and check whatever you want
Upvotes: 1