8

这是我的自定义选择器(StateListDrawable)

<selector
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/common_cell_background" />
    <item
        android:state_pressed="true"
        android:drawable="@drawable/common_cell_background_highlight" />
    <item
        android:state_focused="true"
        android:drawable="@drawable/common_cell_background_highlight" />
    <item
        android:state_selected="true"
        android:drawable="@drawable/common_cell_background_highlight" />
</selector>

common_cell_background 和 common_cell_background_highlight 都是 XML。下面的代码:

common_cell_background.xml

<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/common_cell_background_bitmap"
    android:tileMode="repeat"
    android:dither="true">
</bitmap>

common_cell_background_highlight.xml

<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/common_cell_background_bitmap_highlight"
    android:tileMode="repeat"
    android:dither="true">
</bitmap>

位图也完全相同。高光只是稍微轻一点,没有其他区别。两个位图都是 PNG 文件。

现在我设置

convertView.setBackgroundResource(R.drawable.list_item_background);

这就是问题所在。我的 common_cell_background 没有重复,它被拉伸了。但是,当我触摸列表背景更改为 common_cell_background_highlight 的单元格并猜猜是什么时,有什么令人惊讶的?一切都很好,它应该是重复的。我不知道问题出在哪里,为什么我的背景不重复而突出显示。有什么想法吗?

4

1 回答 1

3

这是错误,已在 ICS 中修复,请参阅此答案:https ://stackoverflow.com/a/7615120/1037294

这是一种解决方法:https ://stackoverflow.com/a/9500334/1037294

请注意,该解决方法仅适用于BitmapDrawable, 对于其他类型的可绘制对象,例如StateListDrawable您需要做额外的工作。这是我使用的:

public static void fixBackgrndTileMode(View view, TileMode tileModeX, TileMode tileModeY) {
    if (view != null) {
        Drawable bg = view.getBackground();

        if (bg instanceof BitmapDrawable) {
            BitmapDrawable bmp = (BitmapDrawable) bg;
            bmp.mutate(); // make sure that we aren't sharing state anymore
            bmp.setTileModeXY(tileModeX, tileModeY);
        }
        else if (bg instanceof StateListDrawable) {
            StateListDrawable stateDrwbl = (StateListDrawable) bg;
            stateDrwbl.mutate(); // make sure that we aren't sharing state anymore

            ConstantState constantState = stateDrwbl.getConstantState();
            if (constantState instanceof DrawableContainerState) {
                DrawableContainerState drwblContainerState = (DrawableContainerState)constantState;
                final Drawable[] drawables = drwblContainerState.getChildren();
                for (Drawable drwbl : drawables) {
                    if (drwbl instanceof BitmapDrawable)
                        ((BitmapDrawable)drwbl).setTileModeXY(tileModeX, tileModeY);
                }
            }
        }
    }
}
于 2012-06-22T09:08:25.757 回答