切换应用程序时如何更改此栏的颜色?

How do I change the color of this bar when switching apps?

添加 Lollipop 后,您现在可以在更改应用程序时更改此 window 的颜色。我不知道它叫什么,因此找不到任何关于它的信息,但如果你看一下图片,你会发现 Keep 应用现在是黄色的。

如何更改此颜色?

Here is a link to the image, it won't let me attach it since I'm new

谢谢

您可以使用 setTaskDescription() 来实现:

setTaskDescription(new ActivityManager.TaskDescription(label, icon, color));

android 文档:

Sets information describing the task with this activity for presentation inside the Recents System UI. When getRecentTasks(int, int) is called, the activities of each task are traversed in order from the topmost activity to the bottommost. The traversal continues for each property until a suitable value is found. For each task the taskDescription will be returned in ActivityManager.TaskDescription.

Parameters taskDescription The TaskDescription properties that describe the task with this activity

https://developer.android.com/reference/android/app/Activity.html#setTaskDescription(android.app.ActivityManager.TaskDescription)

1.normal 方式

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        String title = getString(R.string.app_name);
        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        int color = getResources().getColor(R.color.color_primary);
        setTaskDescription(new ActivityManager.TaskDescription(title, icon, color));
}

2.reflected

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   try {
            Class<?> clazz = Class.forName("android.app.ActivityManager$TaskDescription");
            Constructor<?> cons = clazz.getConstructor(String.class, Bitmap.class, int.class);
            Object taskDescription = cons.newInstance(title, icon, color);

            Method method = ((Object) BaseActivity.this).getClass().getMethod("setTaskDescription", clazz);
            method.invoke(this, taskDescription); 
            } catch (Exception e) {

            }
}

只需将此代码放入目标 activity 的 onCreate 方法中即可:

int color = getResources().getColor(R.color.your_top_bar_color);
setTaskDescription(new ActivityManager.TaskDescription(null, null, color));

请注意上面的代码需要 API 级别 21 (Android 5.0 Lolipop) 或更高级别。如果您还需要支持旧设备,您可以在代码中加上以下条件:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    int color = getResources().getColor(R.color.your_top_bar_color);
    setTaskDescription(new ActivityManager.TaskDescription(null, null, color));
}

另请注意,您需要在每个 activity 中设置顶部栏的颜色,否则在启动另一个 activity 时您的颜色将被重置。 (您可以通过将代码放入某种 BaseActivity 中来缓解此问题,其他 Activity 将从中继承。)

关于此主题的有用文章:https://www.bignerdranch.com/blog/polishing-your-Android-overview-screen-entry/