Andriod实战绘述04-为Fragment定义不同的主题

1.定义Activity的主题

<!-- 为当前的Activity定义一个NoActionBar的主题,这个是必须的,不然后面会报错 -->
<style name="MainTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

2.Fragment中使用Toolbar

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:layout_constraintTop_toTopOf="parent"
        android:background="#611"/>
    <!-- android:background="#611",每一个Fragment中都定义自己的Toolbar,每一个Toolbar都有自己的background,这样就保证了每一个Fragment拥有不同的Toolbar-->
</androidx.constraintlayout.widget.ConstraintLayout>

3.设置状态栏的颜色和图标

//重写Fragment的onCreate方法,保证在调用onCreateView之前就将,状态栏设置成自己所需要的,可以将这个方法提取出来放在BaseFragment中
public void onCreate(Bundle saveInstanceState){
    if(Build.VERSION.SDK_INT>=21){
        Window window=getActivity().getWindow();
        //window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); //将状态栏中的图片和字体设置为黑色
        //window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT); //将状态栏设置为透明的,这样Toolbar就会用android:background="#611"影响状态栏的背景颜色
    }
    super.onCreate(saveInstanceState);
}

4.设置Toolbar

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_dashboard, null);

    Toolbar toolbar = root.findViewById(R.id.toolbar);
    AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
    appCompatActivity.setSupportActionBar(toolbar);//必须使用NoActionBar不然会出现错误
    return root;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值