我需要填充 ListView
带有图标和他们的标题。我在资源中为菜单图标及其标题创建了数组,如:
对于标题:
<array name="menu_title_array">
<item>@string/menu_name_text</item>
</array>
对于图标:
<array name="menu_icons_array">
<item>@drawable/menu_icon_name</item>
</array>
我使用 xml 选择器 drawable 为每个图标创建了一个 drawable,例如:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<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>
现在我正在创建一个包含 title
的菜单项列表和 drawable
来 self 创建的数组 menu_title_array
和 menu_icons_array
喜欢:
TypedArray titles = getResources().obtainTypedArray(R.array.menu_title_array);
TypedArray icons = getResources().obtainTypedArray(R.array.menu_icons_array);
for (int index = 0; index < menuRowText.length(); mainMenuIndex++) {
menuRowItemList.add(new MenuRowItem(icons.getDrawable(index), titles.getString(index ));
}
现在我在适配器中设置标题及其图标 getView()
像这样的方法:
title.setText(menuItem.getTitle());
icon.setImageDrawable(menuItem.getDrawable());
现在,如果我选择一个菜单项,那么图标的状态应该根据 <selector>
改变。我为它创造了。 但它并没有改变它的状态。
如果我创建一个 StateListDrawable
对于每个菜单项,例如:
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));
并将其应用于列表图标,如:
icon.setImageDrawable(states);
然后它会正常工作,因为它正在改变它的激活状态,按下。
请指出我哪里出错了,我不想使用 StateListDrawable
创建可绘制图标对于每个 MenuItem,因为应用程序中会有很多样板代码。
ListView 正在使用 List<MenuRowItem>
填充.这是以下 pojo 的结构:
class MenuRowItem {
private Drawable drawable;
private String title;
MenuRowItem(Drawable drawable, String title) {
this.drawable = drawable;
this.title = title;
}
public Drawable getDrawable() {
return drawable;
}
public String getText() {
return mText;
}
如果需要更多详细信息,请告诉我。
最佳答案
通过在 MenuRowItem
中保留 drawable
的 id
而不是保留 Drawable
对象解决了这个问题。
现在是 MenuRowItem
的 POJO:
class MenuRowItem {
private int drawableResourceId;
private String title;
MenuRowItem(int resourceId, String title) {
this.drawableResourceId = resourceId;
this.title = title;
}
public int getResourceId() {
return drawableResourceId;
}
public String getText() {
return mText;
}
}
我相信 Drawable(enable, activated, normal)
丢失的状态,同时将 drawable 保持为对象。
因此,我在 POJO 中保留了 drawable 的 resourceId,并使用以下方法在适配器中将 drawable 设置为 ImageView:
icon.setImageDrawable(mContext.getResources().getDrawable(item.getResourceId()));
希望对大家有所帮助。如果需要更多信息,请告诉我
关于android - 以编程方式将选择器 xml 资源设置为可绘制到 ImageView 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388428/