【问题标题】:Different Colored Statusbar in each fragment每个片段中的不同颜色状态栏
【发布时间】:2016-05-22 17:14:15
【问题描述】:

如何为每个片段定义不同的状态栏和操作栏颜色?

目前。

应该是什么样子。

【问题讨论】:

  • 看看Toolbar,它比在活动 UI 中硬编码的旧操作栏灵活得多
  • 你只需要改变ActionBar的背景?你试过用ActionBar bar = getActionBar(); bar.setBackgroundDrawable(new ColorDrawable("COLOR"));
  • @CROSP 是的,但是 getActionBar() 在我的片段中不起作用。
  • 当然它不会在Fragment 使用类似getActivity().getActionBar() 的东西我会发布答案解释如何更好地实现这个好吗?

标签: android colors android-actionbar fragment statusbar


【解决方案1】:

首先,我强烈建议您迁移到新方法 - Toolbar。它更加灵活,您可以将其自定义为普通的View

关于您的问题。
您可以通过编程方式获取 ActionBar 对象和 setBackground
这是一个简短的例子
ActionBar bar = getActionBar(); bar.setBackgroundDrawable(new ColorDrawable("COLOR IN HEX 0xFFFF6666 for instance"));

我将展示我将如何实现它。这更多是关于架构和模式。

Fragment 使用一些基类,最好也为Activity 使用基类。让我们考虑

public class BaseFragment extends Fragment

你的片段所在的 Activity 类。

public class MainActivity extends Activity

在这种情况下你必须定义Activity的职责并创建接口

在你的情况下与ActionBar合作

创建界面

public interface ActionBarProvider {
  void setActionBarColor(ColorDrawable color);
}

让你的activity实现这个接口

public class MainActivity extends Activity implements ActionBarProvider {
    public void setActionBarColo(ColorDrawable color) {
      ActionBar bar = getActionBar();
      bar.setBackgroundDrawable(color));
    }
}

最后在BaseFragmentonAttach

public void onAttach(Context context) {
        super.onAttach(context);
        mActionBarProvider = (ActionBarProvider) context;
}

使mActionBarProvider 变量受保护并使每个片段扩展BaseFragment,您可以从任何片段中更改操作栏颜色mActionBarProvider.setActionBarColor(new ColorDrawable());

希望这会有所帮助。

【讨论】:

  • 谢谢,我明天测试一下。 @CRASP
  • 先生,状态栏呢????这个答案似乎适用于操作栏......我有同样的问题......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
相关资源
最近更新 更多