且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎样才能获得当前主题的动作栏背景颜色?

更新时间:2023-01-27 12:10:26

动作条 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();
    }

}