Skip to content

Instantly share code, notes, and snippets.

@dec04
Forked from evelyne24/CustomTextView.java
Created November 26, 2020 07:38
Show Gist options
  • Save dec04/b0a505694a2b0265566a86717c1f90b8 to your computer and use it in GitHub Desktop.
Save dec04/b0a505694a2b0265566a86717c1f90b8 to your computer and use it in GitHub Desktop.
This is how to get the colour from a custom style within a custom style within an Android Theme.
package org.codeandmagic.android.customtheme;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.widget.TextView;
/**
* Created by evelyne24.
*/
public class CustomTextView extends TextView {
public static final String T = "=THEME=";
public CustomTextView(Context context) {
super(context);
init(context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
final TypedValue result = resolveThemeStyle(context.getTheme(), new int[]{R.attr.myDialogStyle,
R.attr.myDialogTitleStyle, android.R.attr.background}, 0, 2);
if (TypedValue.TYPE_INT_COLOR_RGB8 == result.type) {
String strColor = String.format("#%06X", 0xFFFFFF & result.data);
setBackgroundColor(Color.parseColor(strColor));
}
}
private TypedValue resolveThemeStyle(Resources.Theme theme, int[] attrs, int level, int maxLevel) {
TypedValue typedValue = new TypedValue();
theme.resolveAttribute(attrs[level], typedValue, true);
if (typedValue.type == TypedValue.TYPE_REFERENCE) {
Log.i(T, "level " + level + ": found reference " + typedValue.resourceId);
Resources.Theme newTheme = getResources().newTheme();
newTheme.applyStyle(typedValue.resourceId, true);
if (level == maxLevel) {
return typedValue;
} else {
return resolveThemeStyle(newTheme, attrs, level + 1, maxLevel);
}
} else {
return typedValue;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment