根据当前设置的主题获取attr颜色值

col*_*lin 8 android android-theme

在我的活动中,我正在维护一个SuperActivity,我正在设置主题.

public class SuperActivity extends Activity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.MyTheme);
    }
}
Run Code Online (Sandbox Code Playgroud)

的themes.xml

<!-- ImageBackround -->
<style name="Theme.MyTheme" parent="ThemeLight">
    <item name="myBgColor">@color/translucent_black</item>
</style>
Run Code Online (Sandbox Code Playgroud)

现在我想在我的一个孩子活动中获取这种颜色.

正如在这个可能的答案中所提到的,我写道:

int[] attrs = new int[] { R.attr.myBgColor /* index 0 */};
TypedArray ta = ChildActivity.this.obtainStyledAttributes(attrs);
int color = ta.getColor(0, android.R.color.background_light);
String c = getString(color);
ta.recycle();
Run Code Online (Sandbox Code Playgroud)

但每次我得到的默认值为android.R.color.background_light&而不是R.attr.myBgColor.

哪里我做错了.我是否传递了错误的背景ChildActivity.this

Gáb*_*bor 7

你有两个可能的解决方案(一个是你实际拥有的,但我为了完整性而包括两个):

TypedValue typedValue = new TypedValue();
if (context.getTheme().resolveAttribute(R.attr.xxx, typedValue, true))
  return typedValue.data;
else
  return Color.TRANSPARENT;
Run Code Online (Sandbox Code Playgroud)

要么

int[] attribute = new int[] { R.attr.xxx };
TypedArray array = context.getTheme().obtainStyledAttributes(attribute);
int color = array.getColor(0, Color.TRANSPARENT);
array.recycle();
return color;
Run Code Online (Sandbox Code Playgroud)

Color.TRANSPARENT可以是任何其他默认值.是的,正如您所怀疑的那样,背景非常重要.如果你继续获得默认颜色而不是真实颜色,请查看你传递的上下文.我花了几个小时来搞清楚,我试图省去一些打字并且只是使用getApplicationContext()但是它找不到颜色然后......