在前棒棒糖设备的工具栏上添加 elevation/shadow

Add elevation/shadow on toolbar for pre-lollipop devices

我将我的 android 应用程序更新为新的 material 设计,但我还想向工具栏添加一些阴影或高度。似乎有一些(hacky)方法可以通过 images/9-patches 来完成,但我想知道是否可以通过支持库来完成。 (就像 CardView 可以有高度一样)

根据 this 对另一个问题的回答,这可以通过将 Toolbar 包装在 AppBarLayout 中来实现,但这对我不起作用。

我的布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout 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="wrap_content">
    <android.support.v7.widget.Toolbar
            android:id="@+id/Toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>

我也尝试通过 XML 和代码设置高度,但这也不起作用。

如有任何帮助,我们将不胜感激!提前致谢。

更新:

由于我在其他布局中包含了我的工具栏布局,下面是我的主要布局之一:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <include
        layout="@layout/Toolbar" />
    <fragment
        class="OverAllField.XamarinAndroid.Fragments.Planning.PlanningFragment"
        android:id="@+id/PlanningFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

尝试在 activity 布局中使用 AppBarLayout。尝试:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include
            layout="@layout/Toolbar" />
    </android.support.design.widget.AppBarLayout>

    <fragment
        class="OverAllField.XamarinAndroid.Fragments.Planning.PlanningFragment"
        android:id="@+id/PlanningFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

Toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/Toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

对于 Android 5.0 及更高版本:AppBarLayout 自动 provides/gives 布局中的阴影。 您还可以将 AppBarLayout 的高度增加 app:elevation="4dp"

对于 Pre-Lollipop:您可以使用以下 link:https://github.com/vipulasri/Toolbar-Elevation-Pre-Lollipop

注意:工具栏也支持提升到它,使用android:elevation="4dp"


新更新:Appcompat v24.0.0 中,您无法使用 setElevation()app:elevation 因为这些已被弃用。

您现在必须使用 stateListAnimator 属性 来设置高度。

注意:在StateListAnimator中将持续时间设置为1ms避免立面图延迟

appbar_always_elevated.xmlanimator-v21文件夹下res目录.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <objectAnimator android:propertyName="elevation"
                    android:valueTo="8dp" 
                    android:valueType="floatType"
                    android:duration="1"/>
</item>
</selector>

在 AppbarLayout 中:

<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:fitsSystemWindows="true"
        android:stateListAnimator="@animator/appbar_always_elevated"
        android:theme="@style/AppTheme.AppBarOverlay">

</android.support.design.widget.AppBarLayout>

我也在这个问题上浪费了 1 天时间,但我终于想出了一个办法让它发挥作用。

/**
 * Controller for the toolbar which will take care of the drop down shadow also on pre-lollipop devices.
 * <br/>
 * The controller also handles the status bar based on the state of the toolbar.
 * <p/>
 * Created by <b>Negru Ionut Valentin</b> on <b>20/1/2016</b>.
 */
public class ToolbarController {

    private boolean handleStatusBar = false;
    private boolean showTitle = true;

    /**
     * Call this method in onCreate() method of your Activity or in onCreateView() in Fragment
     *
     * @param view
     *         The view into which to look for the toolbar
     * @param activity
     *         The activity for which setup the toolbar
     *
     * @return The toolbar found and customized or {@code null}
     */
    public Toolbar initToolbar(View view, Activity activity) {
        Toolbar mToolbar = (Toolbar) view.findViewById(R.id.toolbar);

        // Valid and visible toolbar - otherwise ignore
        if (null != mToolbar && mToolbar.getVisibility() == View.VISIBLE) {

            int paddingLeft = mToolbar.getPaddingLeft();
            int paddingRight = mToolbar.getPaddingRight();
            int paddingBottom = mToolbar.getPaddingBottom();
            // Set the top padding of the toolbar to match the status bar height
            int paddingTop = new CynnyContextWrapper(activity).getStatusBarHeight();

            mToolbar.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);

            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
                ViewParent parent = mToolbar.getParent();
                if (parent instanceof RelativeLayout) {
                    // Manually create the drop shadow
                    RelativeLayout.LayoutParams params =
                            new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                            Metrics.convertDpToPixel(4, activity));

                    View dropShadow = new View(activity);
                    dropShadow.setBackgroundResource(R.drawable.toolbar_shadow);

                    params.addRule(RelativeLayout.BELOW, R.id.toolbar);

                    ((RelativeLayout) parent).addView(dropShadow, params);
                }
            }

            if (activity instanceof AppCompatActivity) {
                // Check if the Activity actually support ActionBar with Toolbar and set our custom Toolbar for it
                ((AppCompatActivity) activity).setSupportActionBar(mToolbar);

                // Get the actionbar from the activity
                ActionBar actionBar = ((AppCompatActivity) activity).getSupportActionBar();
                if (null != actionBar) {
                    // If the actionbar is valid, customize it
                    actionBar.setDisplayHomeAsUpEnabled(true);
                    actionBar.setHomeButtonEnabled(true);

                    actionBar.setDisplayShowTitleEnabled(this.showTitle);

                    mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_selector);
                }
            }

            if (this.handleStatusBar) {
                // For showing the status bar
                activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            }
        } else if (handleStatusBar) {
            // Force hide the status bar
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        }

        return mToolbar;
    }

    /**
     * Set the flag indicating if the controller should handle or not the status bar.
     *
     * @param handleStatusBar
     *         Flag which indicates if the initialization of the toolbar should also update
     *         the status bar state (if two calls are made for the init, the last one will
     *         be taken into consideration).
     *
     * @return The current toolbar controller.
     */
    public ToolbarController setHandleStatusBar(boolean handleStatusBar) {
        this.handleStatusBar = handleStatusBar;

        return this;
    }

    /**
     * Set the flag indicating if the toolbar should show or hide the title.
     *
     * @param showTitle
     *         Flag indicating if the toolbar should also show the title (the title can be changed after the toolbar
     *         initialization)
     *
     * @return The current toolbar controller.
     */
    public ToolbarController setShowTitle(boolean showTitle) {
        this.showTitle = showTitle;

        return this;
    }
}

在 activity 中,您应该像这样在 onCreate() 方法中使用它:

// Create and customize the Toolbar controller
new ToolbarController().setHandleStatusBar(true).setShowTitle(true)
                                 .initToolbar(((ViewGroup) findViewById(android.R.id.content)).getChildAt(0),
                                              this);

在片段中,您应该像这样在 onCreateView() 方法中使用它:

new ToolbarController().setHandleStatusBar(false).setShowTitle(false).initToolbar(resultView, getActivity());

不要忘记在布局中添加工具栏并使用 android:id="@id/toolbar" 设置它的 ID。如果你想使用另一个 id,你可以自定义控制器并添加另一个使用你提供的 id 的 setter 方法。

我创建了两个工具栏布局:

v21

    <!-- This is the new widget added in Lollipop - use with care -->
    <android.support.v7.widget.Toolbar
            android:id="@id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/TitleToolbarTheme"
            android:background="?android:attr/colorPrimary"
            android:elevation="@dimen/toolbar_elevation"
            />
</merge>

其他

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

    <!-- This is the new widget added in Lollipop - use with care -->
    <android.support.v7.widget.Toolbar
            android:id="@id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/TitleToolbarTheme"
            android:background="?attr/colorPrimary"
            />

</merge>

我在可能的布局中使用它们:

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

希望本文能帮助您解决问题。另请注意,这可以进一步优化,但它对我有用,我不想再在这个问题上浪费时间了。

使用构建文件:


compile 'com.android.support:cardview-v7:23.1.1'

refer this link

拜访xml 添加:

app:cardElevation="8dp"
app:cardCornerRadius="8dp"
app:contentPadding="5dp"

使用 CardView

   <android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="top"
    app:cardCornerRadius="0dp">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">


        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
    </android.support.design.widget.AppBarLayout>
</android.support.v7.widget.CardView>

我认为最好的解决方案是在工具栏下方放置一个渐变阴影视图,并根据设备 sdk 的可见性进行操作。

toolbar.xml

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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="wrap_content"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@android:color/white"
            android:fitsSystemWindows="true"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <TextView
                android:id="@+id/centerTitleToolbarTextView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:maxLines="1"
                android:textColor="@color/color_toolbar"
                android:textSize="@dimen/titleToolbar" />

        </android.support.v7.widget.Toolbar>

        <View
            android:id="@+id/shadow_view"
            android:layout_width="match_parent"
            android:visibility="gone"
            android:layout_height="4dp"
            android:background="@drawable/toolbar_shadow" />

    </LinearLayout>

toolbar_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#c1c1c1"
        android:centerColor="#e6e6e6"
        android:endColor="#f1f1f1"
        android:angle="270" />
</shape>

MainActivity.class

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        findViewById(R.id.shadow_view).setVisibility(View.VISIBLE);
      }

我有一个带有 ToolbarCollapsingToolbarLayout 和一个上下移动但位于 NestedScrollView 上方的类似工具栏的 View,如 https://github.com/k0shk0sh/CoordinatorLayoutExample ]. 我尝试了很多变体。有时阴影会在带有 NestedScrollView 的屏幕上方滚动,有时工具栏会绘制不透明的实心阴影,有时阴影会出现锯齿。无论如何,这是我的解决方案。

说,你有一个布局:

<android.support.design.widget.CoordinatorLayout>
    <android.support.design.widget.AppBarLayout>
         <android.support.design.widget.CollapsingToolbarLayout>
             <android.support.v7.widget.Toolbar>
                 <!-- Toolbar views if needed -->
             </android.support.v7.widget.Toolbar>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <!-- Footer Toolbar views if needed -->

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout>
            <!-- Views -->
        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

    <!-- Add this view. It draws a shadow and aligns top of NestedScrollView -->
    <!-- Set visibility to gone or visible -->
    <View
        android:id="@+id/scroll_shadow"
        android:layout_width="match_parent"
        android:layout_height="4dp"
        android:background="@drawable/shadow"
        android:visibility="gone"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

添加阴影(drawable/shadow.xml):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="90"
        android:endColor="#ffcccccc"
        android:startColor="#00cccccc" />
</shape>

添加这个方法。这里的 scrollShadow 是一个名为 "scroll_shadow":

的视图
private void setShadowVisibility(int visibility) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        scrollShadow.setVisibility(visibility);
    }
}

随心所欲地操纵它。它将在 Lollipop 之前的设备上显示渐变,并在 Android 5.0+.

上显示正常阴影

使用 CoordinatorLayout 时,一个简单的解决方案是使用 AppBarLayoutToolbar 下方的 "shadow" 锚定 ImageView。这甚至适用于 CollapsingToolbarLayout,并且在 "content":

上正确呈现
<CoordinatorLayout>
  <AppBarLayout android:id="@+id/app_bar">
    <Toolbar/>
  </AppBarLayout>
  <include layout="@layout/app_bar_shadow"/>
  <!-- your content usually goes here -->
</CoordinatorLayout>

创建一个 res/layout/app_bar_shadow.xml 文件,该文件将仅在 Lollipop 之前的设备上使用:

<ImageView
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:adjustViewBounds="true"
  app:layout_anchor="@+id/app_bar"
  app:layout_anchorGravity="bottom"
  android:layout_gravity="bottom"
  app:srcCompat="@drawable/shadow_app_bar"
  />

创建一个 "empty" res/layout-v21/app_bar_shadow.xml 文件,用于 Android 5+ 设备:

 <merge/>

最后,一个合适的res/drawable/shadow_app_bar.xml:

<shape>
  <gradient
    android:angle="90"
    android:startColor="#00000000"
    android:endColor="#30000000"
    />
  <size android:height="@dimen/design_appbar_elevation" />
</shape>