工具栏xml阴影(高程)只能在Android 21+上运行

问题描述 投票:1回答:1

所以我添加了导航抽屉,因为它我必须在我的布局xml文件中使用工具栏(而不是使用带有操作栏Theme.AppCompat.Light.DarkActionBar的主题,现在它是Theme.AppCompat.Light.NoActionBar

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"/>

</com.google.android.material.appbar.AppBarLayout>

我发现这个答案在工具栏(AppBarLayouthttps://stackoverflow.com/a/31026359/9766649下添加阴影

但它仅适用于Android 21+

随着Theme.AppCompat.Light.DarkActionBar阴影适用于较旧的Android

所以唯一的解决方案是使用像https://stackoverflow.com/a/26904102/9766649这样的自定义阴影?

android android-toolbar android-elevation
1个回答
0
投票

我决定对较旧和较新的Android使用不同的实现

对于Android 21+(layout-v21 / activity_main.xml):

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        xmlns:android="http://schemas.android.com/apk/res/android">

        <include layout="@layout/toolbar_view"/>

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content"/>

</LinearLayout>

对于较旧的Android(layout / activity_main.xml):

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/toolbar_view"/>

    <FrameLayout android:layout_width="match_parent"
                 android:layout_height="match_parent">

        <include layout="@layout/content"/>

        <View android:layout_width="match_parent"
              android:layout_height="5dp"
              android:background="@drawable/drop_shadow"/>

    </FrameLayout>

</LinearLayout>

toolbar_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppTheme.ActionBar"
    xmlns:android="http://schemas.android.com/apk/res/android"/>

drawable / drop_shadow.xml(为旧版Android的工具栏下方添加高程):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">

    <gradient android:startColor="@android:color/transparent"
              android:endColor="#88666666"
              android:angle="90"/>

</shape>
© www.soinside.com 2019 - 2024. All rights reserved.