问题描述
我试图让我的抽屉式导航栏的背景始终与操作栏的背景颜色相匹配。
I was trying to make my navigation drawer's background always match with the action bar's background color.
这样,每一次,如果主题改变了这两个背景会自动更改。
So that, every time, if the theme changes both background will change automatically.
我看着 R.attr ,但没有发现任何东西。
I looked into R.attr, but didn't find anything.
推荐答案
在动作条
API没有一个方法来检索当前背景可绘制
或颜色。
The ActionBar
API doesn't have a way to retrieve the current background Drawable
or color.
不过,你可以使用 Resources.getIdentifier
来调用 View.findViewById
,检索 ActionBarView
,然后调用 View.getBackground
检索绘制对象
。即便如此,这仍然不会给你的颜色。要做到这一点的唯一方法是将转换绘制对象
到位图
,然后使用某种的找到主色。
However, you could use Resources.getIdentifier
to call View.findViewById
, retrieve the ActionBarView
, then call View.getBackground
to retrieve the Drawable
. Even so, this still won't give you the color. The only way to do that would be to convert the Drawable
into a Bitmap
, then use some sort of color analyzer to find the dominant color.
下面是检索的一个例子动作条
绘制对象
。
Here's an example of retrieving the ActionBar
Drawable
.
final int actionBarId = getResources().getIdentifier("action_bar", "id", "android");
final View actionBar = findViewById(actionBarId);
final Drawable actionBarBackground = actionBar.getBackground();
不过,这似乎是最简单的解决办法是创建自己的属性,并把它应用在你的主题。
But it seems like the easiest solution would be to create your own attribute and apply it in your themes.
下面是一个例子:
自定义属性
<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
,适用安卓背景
属性是这样的:
Then in the layout that contains your DrawerLayout
, apply the android:background
attribute like this:
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();
}
}
这篇关于我怎样才能获得当前主题的动作栏背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!