首页 > Android 一个关于在自定义视图中重复使用drawable对象导致背景错乱的问题

Android 一个关于在自定义视图中重复使用drawable对象导致背景错乱的问题

在我自定义视图中,有一个通过代码循环创建的按钮列表,每一个按钮都给设置上背景,背景通过自定义属性设置。大致代码如下:

<declare-styleable name="CustomView">
    <attr name="background" format="color|reference" />
</declare-styleable>

...

Drawable background = typedArray.getDrawable(R.styleable.CustomView_background);
if (background == null) {
    background = mContext.getDrawable(R.drawable.selector_default_bg);
}

...

LinearLayout btnList = new LinearLayout(mContext);
...
for (...) {
    Button btn = new Button(mContext);
    ...
    btn.setBackground(background);å
    ...
    btnList.addView(btw); 
}

运行后发现,当点击其中的一个按钮时,其他的按钮的背景跟着变了。经过一番的查找,发现是因为所有的按钮的背景,都是用的同一个drawable对象,所以这才导致了按下时背景错乱。

有没有办法或API能解决这个问题?
难道需要拷贝drawable对象?

虚心向大家请假,谢谢!!!


background.getConstantState().newDrawable();

这行代码能进行拷贝drawable


对象引用问题,把background变量定义及初始化放到for循环中,每一个Button都有一个自己对应的background对象,就不会有背景错乱的问题了

【热门文章】
【热门文章】