2016-08-15 13 views
0

私は、この属性はattrs.xmlに宣言している:カスタム属性(attrs.xml)の値を取得する方法は?

<resources> 
    <attr name="customColorPrimary" format="color" value="#076B07"/> 
</resources> 

私はそれが「#076B07」であるべき値、ですが、代わりに私は整数を取得しています取得する必要があります:「2130771968」

私はこの方法で値にアクセスしています:

int color = R.attr.customColorFontContent; 

この属性の本当の価値を得る正しい方法はありますか?

はあなたに

答えて

2

ありがとう整数R.attr.customColorFontContentアプリがコンパイルされたときにAndroidのメーカーによって生成されたリソース識別子であるとしていいえ、これは、正しい方法ではありません。

代わりに、テーマの属性に関連付けられている色を取得する必要があります。これを行うには以下のクラスを使用します。

public class ThemeUtils { 
    private static final int[] TEMP_ARRAY = new int[1]; 

    public static int getThemeAttrColor(Context context, int attr) { 
     TEMP_ARRAY[0] = attr; 
     TypedArray a = context.obtainStyledAttributes(null, TEMP_ARRAY); 
     try { 
      return a.getColor(0, 0); 
     } finally { 
      a.recycle(); 
     } 
    } 
} 

あなたは、このようにそれを使用することができます:

ThemeUtils.getThemeAttrColor(context, R.attr.customColorFontContent); 
+0

はありがとうございました!そんなに! – NullPointerException

+0

TR4Android属性のデフォルト値を設定する方法は知っていますか?設定値= "#076B07"は機能しません – NullPointerException

+0

問題はありません。私が助けることができてうれしいです。 – TR4Android

0

次のようにあなたがcolor属性にアクセスする必要があります

public MyCustomView(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0); 
    try { 
     color = ta.getColor(R.styleable.MyCustomView_customColorPrimary, android.R.color.white); //WHITE IS THE DEFAULT COLOR 
    } finally { 
     ta.recycle(); 
    } 

    ... 
} 
関連する問題