【问题标题】:Unable to change the color of the status bar in the TabLayout?无法更改 TabLayout 中状态栏的颜色?
【发布时间】:2026-01-25 08:55:01
【问题描述】:

我想更改TabLayout 中状态栏的颜色,但出现错误?

错误代码截图 http://s3.picofile.com/file/8370099418/Screenshot_from_2019_08_20_14_57_39.jpg

    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tab.getPosition() == 0) {
                toolbar.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
                tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getWindow().getStatusBarColor(ContextCompat.getColor(MainActivity.this , R.color.colorPrimaryDark));
                }
            } else if (tab.getPosition() == 1) {
                toolbar.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.Yellow));
                tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.Yellow));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getWindow().getStatusBarColor(ContextCompat.getColor(MainActivity.this, R.color.YellowDark));
                }
            }
        }

【问题讨论】:

  • Color.parseColor("#4CAF50") 像这样使用颜色
  • 使用 setStatusBarColor() 代替 getStatusBarColor()。
  • 窗口窗口 = getActivity().getWindow(); statusBarColor = window.getStatusBarColor(); window.setStatusBarColor(getResources().getColor(R.color.action_mode_status_bar));

标签: android android-studio colors android-tablayout


【解决方案1】:

我想你必须使用 tabLayout.setStatusBarColor(ContextCompat.getColor(MainActivity.this,R.color.YellowDark))

【讨论】:

    【解决方案2】:

    Java:

    if (Build.VERSION.SDK_INT >= 21) {
                Window window = this.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark));
            }
    

    科特林:

    if (Build.VERSION.SDK_INT >= 21) {
                val window = this.window
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                window.statusBarColor = this.resources.getColor(R.color.colorPrimaryDark)
            }
    

    【讨论】: