custom attribute on custom Button does not show

女生的网名这么多〃 提交于 2019-12-02 10:24:47

The custom button is offset, clipped and it is not clickable

That's due to your use of the constructors. The Button class does chain between its constructors but it doesn't pass 0 to the last constructor as the style(from the second constructor which is the one used), it passes an internal style(what makes a visual Button in the end). If you were to pass:

this(context, attrs, android.R.attr.buttonStyle);

the Button should be ok.

The color filter is not applied

The code for setting the color filter should work with no problems after you make the correction above. When you'll set the filter you'll see that both buttons will have the filter applied to them(as they have the same bitmap(I'm assuming you use an image)). This is happening because the drawables of the same type share a constant state. You can read more from Romain Guy's explanation here:

getBackground().mutate().setColorFilter(backGroundColor, Mode.MULTIPLY);

Let me know if this solves the problem(from what I understood):

public static class MyButton extends Button {

    private int backGroundColor;
    private StateListDrawable mSld;
    private PorterDuffColorFilter mColorFilter;
    private boolean mHandled = false;

    public MyButton(Context context, AttributeSet attrs, int defStyle) {
        // ...
        try {
            //...
            mSld = (StateListDrawable) getBackground();
            mColorFilter = new PorterDuffColorFilter(backGroundColor,
                    Mode.MULTIPLY);
            mSld.setColorFilter(mColorFilter);
        } finally {
            a.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!mHandled) {
            final Drawable current = mSld.getCurrent();
            current.mutate();
            current.setColorFilter(mColorFilter);
            mHandled = true;
        }
        super.onDraw(canvas);
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!