[英]Programmatically setting selector xml resourse as drawable to ImageView is not working
我需要用圖標及其標題填充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>
現在,我正在創建一個MenuItems列表,其中包含我創建了menu_title_array
和menu_icons_array
數組的title
和drawable
menu_title_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);
則它在更改狀態下處於激活狀態,按下該按鈕即可正常工作。
請提出我要去哪里的錯誤,我不想為每個MenuItem使用StateListDrawable
創建圖標可繪制,因為應用程序中會有很多樣板代碼。
使用List<MenuRowItem>
填充ListView。 以下是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;
}
讓我知道是否需要更多詳細信息。
通過保持解決問題id
的drawable
在MenuRowItem
,而不是保持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()));
希望它會幫助某人。 讓我知道是否需要更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.