2016-09-27 117 views
1

继使用typedarray是我styelable.xml无法自定义视图

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <declare-styleable name="MaterialIndicator"> 
    <attr name="mi_indicatorRadius" format="dimension|reference" /> 
    <attr name="mi_indicatorPadding" format="dimension|reference" /> 
    <attr name="mi_indicatorColor" format="color|reference" /> 
    </declare-styleable> 

</resources> 

林指上述styelable如下,

public MaterialIndicator(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
     selectedIndicatorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 
     indicatorPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 
     indicatorPaint.setColor(Color.BLACK); 
     indicatorPaint.setAlpha((int) (deselectedAlpha * 255)); 
     selectorRect = new RectF(); 
     if (isInEditMode()) { 
      count = 3; 
     } 
     TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MaterialIndicator, 0, R.style.MaterialIndicator); 
     try { 
      selectedIndicatorPaint.setColor(typedArray.getColor(R.styleable.MaterialIndicator_mi_indicatorColor, 0)); 
     } finally { 
      typedArray.recycle(); 
     } 
    } 

但它引发以下错误消息

引起:java.lang.UnsupportedOperationException:无法转换为 颜色:类型= 0x1 at android.content.res.TypedArray.getColor(TypedArray.java:339)

我该如何解决这个问题?

+0

如果从XML文件中删除'reference'我的意思是,你只需要的格式会发生什么=”颜色“ – mt0s

+0

仍然是一个问题持续 – Learner

+0

哪一行是339? – mt0s

回答

1

从源代码here

* @throws UnsupportedOperationException if the attribute is defined but is * not an integer color or color state list.

变更色彩值:

  selectedIndicatorPaint.setColor(typedArray.getColor(R.styleable.MaterialIndicator_mi_indicatorColor, 0)); 

从零到的颜色值。在显色值是:

Color A color value defined in XML. The color is specified with an RGB value and alpha channel. You can use a color resource any place that accepts a hexadecimal color value. You can also use a color resource when a drawable resource is expected in XML (for example, android:drawable="@color/green").

https://developer.android.com/guide/topics/resources/more-resources.html#Color

编辑:像#80ff0000的东西应该工作

+0

它的工作原理,但我有颜色资源为?android:attr/colorAccent因此它坠毁 – Learner

+0

你在哪里'?android:attr/colorAccent'? – mt0s

+0

im在styles.xml中有它 – Learner

相关问题