【问题标题】:Android custom view attribute shared between instances?实例之间共享的Android自定义视图属性?
【发布时间】:2017-01-26 13:02:48
【问题描述】:

我在应用程序周围使用了一个自定义进度条,它有一个用于设置不确定颜色的属性。由于我正在使用支持库,因此我也尝试在较旧的 android 版本上为进度条着色。

在 attrs 我有类似的东西:

<declare-styleable name="TestView">
        <attr name="testColor" format="color"/>
</declare-styleable>

声明视图时:

<com.TestView
  ....
  app:testColor="#color"
/>

那么我的自定义视图是这样的:

public class TestView extends ProgressBar {

    public TestView(Context context) {
        super(context);
        applyTint(Color.WHITE);
    }

    public TestView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TestView, 0, 0);

        try {
            applyTint(attributes.getColor(R.styleable.TestView_testColor, Color.WHITE));
        } finally {
            attributes.recycle();
        }

    }

    public TestView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, android.support.design.R.style.Base_Widget_AppCompat_ProgressBar);
        TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TestView, 0, 0);

        try {
            applyTint(attributes.getColor(R.styleable.TestView_testColor, Color.WHITE));
        } finally {
            attributes.recycle();
        }
    }

    private void applyTint(int color) {
        if (Build.VERSION.SDK_INT >= 21) {
            setIndeterminateTintList(ColorStateList.valueOf(color));
        } else {
            getIndeterminateDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);
        }
    }
}

我遇到的问题是,颜色的属性似乎在 TestView 的实例之间以某种方式共享。 如何让每个视图保持自己的属性值?

稍后编辑:似乎在 android 6 上工作正常,但在 4.4.2 上失败

【问题讨论】:

  • 所有SDK都存在这个问题吗?
  • 似乎与 Android 5.0 之前的版本有关。现在它发生在我的 4.4.2 测试设备上

标签: android android-custom-view android-attributes


【解决方案1】:

https://stackoverflow.com/a/37434219/379865得到答案

基本上我必须更新我的色调应用代码:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   DrawableCompat.setTint(DrawableCompat.wrap(getIndeterminateDrawable()), color);
else {
   DrawableCompat.wrap(getIndeterminateDrawable()).mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}

【讨论】:

    猜你喜欢
    • 2014-06-14
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    相关资源
    最近更新 更多