I need to populate ListView with icon and their title. I have created array in resources for menu icon and their title like:
For titles:
<array name="menu_title_array">
<item>@string/menu_name_text</item>
</array>
For icons:
<array name="menu_icons_array">
<item>@drawable/menu_icon_name</item>
</array>
I have created a drawable for each icon using xml selector drawable like:
<selector xmlns:android="http://ift.tt/nIICcg">
<item android:drawable="@drawable/icon_name_disabled" android:state_enabled="false"/>
<item android:drawable="@drawable/icon_name_press" android:state_pressed="true"/>
<item android:drawable="@drawable/icon_name_press" android:state_activated="true"/>
<item android:drawable="@drawable/icon_name"/>
</selector>
Now I am creating a list of MenuItems that contains title and drawable from array that I have created menu_title_array and menu_icons_arraylike:
TypedArray titles = getResources().obtainTypedArray(R.array.menu_title_array);
TypedArray icons = getResources().obtainTypedArray(R.array.menu_icons_array);
--> in for loop:
menuRowItemList.add(new MenuRowItem(icons.getDrawable(mainMenuIndex), titles.getString(mainMenuIndex));
Now I am setting title and their icon in adapter getView() method like this:
title.setText(menuItem.getTitle());
icon.setImageDrawable(menuItem.getDrawable());
Now if I select a menu item then state of the icon should change according to the <selector> I had created for it. But it's not changing it's state.
If I create a StateListDrawable for each menu item like:
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
mContext.getResources().getDrawable(R.drawable.icon_name_press));
states.addState(new int[] {android.R.attr.state_activated},
mContext.getResources().getDrawable(R.drawable.icon_name_press));
states.addState(new int[] { },
mContext.getResources().getDrawable(R.drawable.icon_name));
and apply it to list icon like:
icon.setImageDrawable(states);
then it is working correctly as it's changing it's state activated, pressed.
Please suggest where I am going wrong, I not want to create icon drawable using StateListDrawable for each MenuItem, as there will be lot of boiler plate code in app. Let me know if more details needed.
Aucun commentaire:
Enregistrer un commentaire