我试图让我的导航抽屉背景始终与操作栏背景颜色相匹配。这样,每次主题更改时,两个背景都会自动更改。我查看了R.attr,但没有找到任何内容。
ActionBar
API没有一种方法来检索当前的背景Drawable
或颜色。但是,您可以使用Resources.getIdentifier
调用View.findViewById
,检索ActionBarView
,然后调用View.getBackground
来检索Drawable
。即使这样,这仍然无法给您颜色。唯一的方法是将Drawable
转换为Bitmap
,然后使用某种颜色分析器查找主要颜色。ActionBar
Drawable
的示例。 final int actionBarId = getResources().getIdentifier("action_bar", "id", "android");
final View actionBar = findViewById(actionBarId);
final Drawable actionBarBackground = actionBar.getBackground();
不过,最简单的解决方案似乎是创建自己的属性并将其应用于您的主题。
以下是一个示例:
自定义属性
<attr name="drawerLayoutBackground" format="reference|color" />
初始化属性
<style name="Your.Theme.Dark" parent="@android:style/Theme.Holo">
<item name="drawerLayoutBackground">@color/your_color_dark</item>
</style>
<style name="Your.Theme.Light" parent="@android:style/Theme.Holo.Light">
<item name="drawerLayoutBackground">@color/your_color_light</item>
</style>
然后在包含你的DrawerLayout
的布局中,像这样应用android:background
属性:
android:background="?attr/drawerLayoutBackground"
或者您可以使用 TypedArray
来获取它。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TypedArray a = obtainStyledAttributes(new int[] {
R.attr.drawerLayoutBackground
});
try {
final int drawerLayoutBackground = a.getColor(0, 0);
} finally {
a.recycle();
}
}