首页 > 解决方案 > Android - 为每个片段提供工具栏

问题描述

我想创建 3 个片段,如下图所示:

带有工具栏和状态栏的片段

透明工具栏和状态栏

透明工具栏不是状态栏

片段的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/fragment_root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorYellow"
    >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:elevation="4dp"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"/>

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar"
        android:id="@+id/fragment_container_layout">
    </FrameLayout>

</RelativeLayout>

我的主题如下:

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    <style name="MyTranparentTheme" parent="AppTheme">
        <item name="windowActionBarOverlay">true</item>
        <item name="android:windowTranslucentStatus">true</item>
    </style> </resources>

我在 AndroidManifest.xml 中设置了应用程序的主题:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

片段构造函数签名在这里:

new BlankFragment(isTranslucentHeaderbar, isTranslucentStatusbar)

如何创建这些片段?

我创建非半透明工具栏和状态栏在这里:

在此处输入图像描述

但我无法使用半透明工具栏创建片段。我的 onCreateView 代码如下:

View view = inflater.inflate(R.layout.fragment_sensor_light, container, false);

Toolbar toolbar = view.findViewById(R.id.toolbar);

toolbar.setTitle("Fragment toolbar");
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity)getActivity()).getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(getContext(), R.color.translucentColor)));
return view;

如果我在清单文件中将主题设置为 MyTransparentTheme,则 ss 如下:

在此处输入图像描述

标签: androidandroid-fragmentsandroid-actionbarandroid-toolbar

解决方案


推荐阅读