2015-10-10 7 views
10

TextViewのテキストの色をプログラムで?android:textColorPrimaryに設定するにはどうすればよいですか?プログラムでテキストの色を1次アンドロイドに設定

私は以下のコードを試しましたが、textColorPrimaryとtextColorPrimaryInverseの両方でテキストの色を常に白に設定しています(両方とも白ではなく、XMLでチェックしました)。

TypedValue typedValue = new TypedValue(); 
Resources.Theme theme = getActivity().getTheme(); 
theme.resolveAttribute(android.R.attr.textColorPrimaryInverse, typedValue, true); 
int primaryColor = typedValue.data; 

mTextView.setTextColor(primaryColor); 
+0

通常、私はTextViewクラスを拡張しています。アプリ内のどこにでも使用しています。 TextViewクラスでは、デフォルトの色、フォントなどの設定を行います。もう1つの方法は、静的変数を目的の色で作成し、.setTextColor()を使用することです。どこにでも。 3番目の方法は、新しいAndroid Studio(1.4)テーマデバッガを使用してテーマを編集することです。私はこれが直接的な答えではないことを知っていますが、それは良い仕事かもしれません。 –

+0

私はどこでも 'setTextColor'を使うつもりはありません。私は特定の 'TextView'のためにセカンダリからプライマリに色を設定したいと思います。 – jaibatrik

+0

あなたはそれを...として使用しようとすることができます.. 'mTextView.setTextColor(android.R.attr.textColorPrimary);' –

答えて

14

は、最後に私がテーマの一次テキストの色を取得するには、次のコードを使用 -

// Get the primary text color of the theme 
TypedValue typedValue = new TypedValue(); 
Resources.Theme theme = getActivity().getTheme(); 
theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true); 
TypedArray arr = 
     getActivity().obtainStyledAttributes(typedValue.data, new int[]{ 
       android.R.attr.textColorPrimary}); 
int primaryColor = arr.getColor(0, -1); 
+5

最後の行 'arr.recycle()'の後にTypedArrayをリサイクルすることを忘れないでください。 – sorianiv

3

これはそれを行うための正しい方法です。

デフォルト値textColorPrimaryはColorではなくColorStateListなので、属性がresourceIdまたはcolor値に解決されたかどうかを確認する必要があります。

public static TypedValue resolveThemeAttr(Context context, @AttrRes int attrRes) { 
    Theme theme = context.getTheme(); 
    TypedValue typedValue = new TypedValue(); 
    theme.resolveAttribute(attrRes, typedValue, true); 
    return typedValue; 
} 

@ColorInt public static int resolveColorAttr(Context context, @AttrRes int colorAttr) { 
    TypedValue resolvedAttr = resolveThemeAttr(context, colorAttr); 
    // resourceId is used if it's a ColorStateList, and data if it's a color reference or a hex color 
    int colorRes = resolvedAttr.resourceId != 0 ? resolvedAttr.resourceId : resolvedAttr.data; 
    return ContextCompat.getColor(context, colorRes); 
} 
関連する問題