StateListDrawable用于切换colorfilters

时间:2011-05-16 14:04:42

标签: java android android-layout android-tabhost colorfilter

我想创建在TabHost中使用的自定义按钮。我一直在尝试使用相同的图像资源(png),但是根据状态改变colorfilter。所以我把它作为自定义按钮的布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">
    <ImageView android:id="@+id/tab_icon"
        android:layout_centerInParent="true" android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView android:id="@+id/tab_text" android:layout_below="@id/tab_icon"
        android:layout_centerHorizontal="true" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

在我的活动中,我添加了这样的标签:

tabHost.addTab(tabHost.newTabSpec(TAB_NAME_NEWS).setIndicator(buildTab(R.drawable.tab_icon_news, R.string.news))
          .setContent(newsIntent));

这是'buildTab'方法:

private final static int[] SELECTED = new int[] { android.R.attr.state_selected };
private final static int[] IDLE = new int[] { -android.R.attr.state_selected };

private View buildTab(int icon, int label) {
    LayoutInflater inflater = LayoutInflater.from(this);
    View view = inflater.inflate(R.layout.tab_button, null);
    StateListDrawable drawable = new StateListDrawable();

    Drawable selected = getResources().getDrawable(icon);
    selected.mutate();
    selected.setBounds(0, 0, selected.getIntrinsicWidth(), selected.getIntrinsicHeight());
    selected.setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x0000FF00));
    drawable.addState(SELECTED, selected);

    Drawable idle = getResources().getDrawable(icon);
    idle.mutate();
    idle.setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x000000FF));
    drawable.addState(IDLE, idle);

    ((ImageView) view.findViewById(R.id.tab_icon)).setImageDrawable(drawable);
    ((TextView) view.findViewById(R.id.tab_text)).setText(getString(label));
    return view;
}

在选定状态下,图像应为完全绿色(0x0000FF00),在非选定状态下,图像应为蓝色(0x000000FF)。

问题是彩色滤镜似乎被完全忽略了。在任何情况下我都看不出颜色的变化。

我也试图通过在android:tint上设置<ImageView/>属性来获得相同的结果,但显然你不能在那里使用对<selector>的引用,因为它会抛出一个NumberFormatException

我看不出我做错了什么,所以任何帮助都会受到赞赏。

5 个答案:

答案 0 :(得分:15)

好的,我从来没有上面的代码可以工作,所以这就是我最终做的事情。

首先,我将LayerDrawable子类化:

public class StateDrawable extends LayerDrawable {

    public StateDrawable(Drawable[] layers) {
        super(layers);
    }

    @Override
    protected boolean onStateChange(int[] states) {
        for (int state : states) {
            if (state == android.R.attr.state_selected) {
                super.setColorFilter(Color.argb(255, 255, 195, 0), PorterDuff.Mode.SRC_ATOP);
            } else {
                super.setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_ATOP);
            }
        }
        return super.onStateChange(states);
    }

    @Override
    public boolean isStateful() {
        return true;
    }

}

我将buildTab()方法更改为以下内容:

private View buildTab(int icon, int label) {
    LayoutInflater inflater = LayoutInflater.from(this);
    View view = inflater.inflate(R.layout.tab_button, null);
    ((ImageView) view.findViewById(R.id.tab_icon)).setImageDrawable(new StateDrawable(new Drawable[] { getResources()
          .getDrawable(icon) }));
    ((TextView) view.findViewById(R.id.tab_text)).setText(getString(label));
    return view;
}

我仍然像这样添加标签:

Intent fooIntent = new Intent().setClass(this, FooActivity.class);
tabHost.addTab(tabHost.newTabSpec(TAB_NAME_INFO).setIndicator(buildTab(R.drawable.tab_icon_info, R.string.info)).setContent(infoIntent));

这对我有用,与android 1.6兼容。

答案 1 :(得分:10)

无法将colorfilter直接应用于drawable也无法解决问题。对我有用的是将图像作为位图,使用相同的度量创建空的第二个,为第二个定义画布,将该colorfilter应用于绘制对象,并在第二个上绘制第一个位图。最后从新的Bitmap创建一个BitmapDrawable,你就完成了。这是代码

    ImageButton imageButton = (ImageButton)findViewById(R.id.aga);

    Bitmap one = BitmapFactory.decodeResource(getResources(), R.drawable.pen_circle);
    Bitmap oneCopy = Bitmap.createBitmap(one.getWidth(), one.getHeight(), Config.ARGB_8888);

    Canvas c = new Canvas(oneCopy);
    Paint p = new Paint();
    p.setColorFilter(new LightingColorFilter(Color.CYAN, 1));
    c.drawBitmap(one, 0, 0, p);

    StateListDrawable states = new StateListDrawable();
    states.addState(new int[] {android.R.attr.state_pressed}, new BitmapDrawable(oneCopy));
    states.addState(new int[] { }, imageButton.getDrawable());
    imageButton.setImageDrawable(states);

答案 2 :(得分:9)

这是我的课程,黑客入侵以支持ColorFilter:

用法:

final Drawable icon = getResources().getDrawable(iconResId);
final Drawable filteredIcon = // this is important
        icon.getConstantState().newDrawable();
final FilterableStateListDrawable selectorDrawable =
        new FilterableStateListDrawable();
selectorDrawable.addState(ICON_STATE_SELECTED, filteredIcon,
        new PorterDuffColorFilter(mIconOverlayColor, PorterDuff.Mode.SRC_ATOP));
selectorDrawable.addState(ICON_STATE_DEFAULT, icon);

如您所见,ColorFilter未直接应用于drawable,它会在向选择器Drawable添加状态时与其关联。

这里最重要的是

  • 您需要从常量状态创建一个新的drawable,否则您将修改常量状态,从而修改您的活动周围的任何实例。
  • 你需要使用我的自定义addState方法,它与框架方法addState的名称相同,但我添加了一个额外的参数(ColorFilter)。框架超类中不存在此方法!

代码(脏,但对我有用):

/**
 * This is an extension to {@link android.graphics.drawable.StateListDrawable} that workaround a bug not allowing
 * to set a {@link android.graphics.ColorFilter} to the drawable in one of the states., it add a method
 * {@link #addState(int[], android.graphics.drawable.Drawable, android.graphics.ColorFilter)} for that purpose.
 */
public class FilterableStateListDrawable extends StateListDrawable {

    private int currIdx = -1;
    private int childrenCount = 0;
    private SparseArray<ColorFilter> filterMap;

    public FilterableStateListDrawable() {
        super();
        filterMap = new SparseArray<ColorFilter>();
    }

    @Override
    public void addState(int[] stateSet, Drawable drawable) {
        super.addState(stateSet, drawable);
        childrenCount++;
    }

    /**
     * Same as {@link #addState(int[], android.graphics.drawable.Drawable)}, but allow to set a colorFilter associated to this Drawable.
     *
     * @param stateSet    - An array of resource Ids to associate with the image.
     *                    Switch to this image by calling setState().
     * @param drawable    -The image to show.
     * @param colorFilter - The {@link android.graphics.ColorFilter} to apply to this state
     */
    public void addState(int[] stateSet, Drawable drawable, ColorFilter colorFilter) {
        // this is a new custom method, does not exist in parent class
        int currChild = childrenCount;
        addState(stateSet, drawable);
        filterMap.put(currChild, colorFilter);
    }

    @Override
    public boolean selectDrawable(int idx) {
        if (currIdx != idx) {
            setColorFilter(getColorFilterForIdx(idx));
        }
        boolean result = super.selectDrawable(idx);
        // check if the drawable has been actually changed to the one I expect
        if (getCurrent() != null) {
            currIdx = result ? idx : currIdx;
            if (!result) {
                // it has not been changed, meaning, back to previous filter
                setColorFilter(getColorFilterForIdx(currIdx));
            }
        } else if (getCurrent() == null) {
            currIdx = -1;
            setColorFilter(null);
        }
        return result;
    }

    private ColorFilter getColorFilterForIdx(int idx) {
        return filterMap != null ? filterMap.get(idx) : null;
    }
}

我已经打开了一个关于此问题的错误:https://code.google.com/p/android/issues/detail?id=60183

更新:自从棒棒糖以来,我已经在框架中修复了这个bug。 我认为修复提交是这样的:https://android.googlesource.com/platform/frameworks/base/+/729427d%5E!/

或在Github上:https://github.com/android/platform_frameworks_base/commit/729427d451bc4d4d268335b8dc1ff6404bc1c91e

我的解决方法在Lollipop之后仍然可以使用,它只是不使用谷歌的修复程序。

答案 3 :(得分:1)

这是我对Mopper代码的修改。我们的想法是ImageView在用户触摸时获取滤色器,并在用户停止触摸时删除滤色器。

class PressedEffectStateListDrawable extends StateListDrawable {

    private int selectionColor;

    public PressedEffectStateListDrawable(Drawable drawable, int selectionColor) {
        super();
        this.selectionColor = selectionColor;
        addState(new int[] { android.R.attr.state_pressed }, drawable);
        addState(new int[] {}, drawable);
    }

    @Override
    protected boolean onStateChange(int[] states) {
        boolean isStatePressedInArray = false;
        for (int state : states) {
            if (state == android.R.attr.state_pressed) {
                isStatePressedInArray = true;
            }
        }
        if (isStatePressedInArray) {
            super.setColorFilter(selectionColor, PorterDuff.Mode.MULTIPLY);
        } else {
            super.clearColorFilter();
        }
        return super.onStateChange(states);
    }

    @Override
    public boolean isStateful() {
        return true;
    }
}

用法:

Drawable drawable = new FastBitmapDrawable(bm);
imageView.setImageDrawable(new PressedEffectStateListDrawable(drawable, 0xFF33b5e5));

答案 4 :(得分:1)

这是我对@Malachiasz代码的变体,这使您可以选择要应用于基本drawable的状态和颜色的任意组合。

public class ColorFilteredStateDrawable extends StateListDrawable {

    private final int[][] states;
    private final int[] colors;

    public ColorFilteredStateDrawable(Drawable drawable, int[][] states,  int[] colors) {
        super();
        drawable.mutate();
        this.states = states;
        this.colors = colors;
        for (int i = 0; i < states.length; i++) {
            addState(states[i], drawable);
        }
    }

    @Override
    protected boolean onStateChange(int[] states) {
        if (this.states != null) {
            for (int i = 0; i < this.states.length; i++) {
                    if (StateSet.stateSetMatches(this.states[i], states)) {
                        super.setColorFilter(this.colors[i], PorterDuff.Mode.MULTIPLY);
                        return super.onStateChange(states);
                    }
            }
            super.clearColorFilter();
        }
        return super.onStateChange(states);
    }

    @Override
    public boolean isStateful() {
        return true;
    }
}