Android:在应用程序处于后台时更改状态栏的颜色

时间:2016-05-25 15:55:35

标签: android background-process statusbar

我只能找到解决方案,让状态栏在应用运行时更改颜色。我已经成功完成了它,但是当应用程序进入后台时(例如当用户点击主页按钮时),我需要它保持新的颜色。类似于当你打电话给某人并按下主页按钮时状态栏改变颜色的方式。

在我的OnCreate方法中,我有:

    Window window = this.getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

    SystemBarTintManager tintManager = new SystemBarTintManager(this);
    tintManager.setStatusBarTintEnabled(true);
    tintManager.setStatusBarTintColor(Color.GREEN);
    tintManager.setStatusBarTintEnabled(true);

所以我发现的解决方案在很大程度上取决于应用程序的开放性。当用户点击主页按钮时,状态栏的颜色会缩小"与应用程序的其余部分。

2 个答案:

答案 0 :(得分:0)

在您的活动中添加以下方法:

@Override
protected void onPause() {
    super.onPause();

    // put your code here
}

答案 1 :(得分:-1)

尝试一下,为我工作!

int statusBarHeight = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) statusBarHeight = getResources().getDimensionPixelSize(resourceId);

final WindowManager.LayoutParams parameters = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT,
        statusBarHeight,
        WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,   // Allows the view to be on top of the StatusBar
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,    // Keeps the button presses from going to the background window and Draws over status bar
        PixelFormat.TRANSLUCENT);
parameters.gravity = Gravity.TOP | Gravity.CENTER;

LinearLayout ll = new LinearLayout(this);
ll.setBackgroundColor(Color.TRANSPARENT);
LinearLayout.LayoutParams layoutParameteres = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
ll.setLayoutParams(layoutParameteres);

TextView tv = new TextView(this);
ViewGroup.LayoutParams tvParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
tv.setLayoutParams(tvParameters);
tv.setTextColor(Color.WHITE);
tv.setGravity(Gravity.CENTER);
tv.setText("123");
ll.addView(tv);

WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.addView(ll, parameters);

源:https://stackoverflow.com/a/45392031/13621167