3

我在使用新的 CardView 时遇到了一些问题

这就是我目前的情况:我想使用 CardView 为所有设备提供一个浮动操作按钮(也是 Pre-Lollipop)

我的活动布局看起来像这样

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:cardview="http://schemas.android.com/apk/res-auto"
         android:id="@+id/container"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:background="#cdcdcd"
         android:focusable="false">

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


<android.support.v7.widget.CardView
    android:layout_width="58dp"
    android:layout_height="58dp"
    cardview:cardPreventCornerOverlap="true"
    android:layout_gravity="bottom|right"
    android:layout_marginBottom="16dp"
    android:layout_marginRight="18dp"
    cardview:cardCornerRadius="29dp"
    cardview:cardBackgroundColor="?attr/colorPrimary">

    <ImageView
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_gravity="center"
        android:layout_margin="12dp"
        android:src="@android:drawable/ic_menu_edit"/>
</android.support.v7.widget.CardView>

在 Nexus 5 (4.4.4) 上运行应用程序,屏幕如下所示: 带有 FAB 的 MainActivity - 没有自定义 cardView 角半径

现在我想通过在 xml 中设置它来设置 cardElevation

cardview:cardElevation="8dp"

启动应用程序后,按钮如下所示(不再是圆圈): 带有 FAB 的 MainActivity - 自定义 cardView 角半径 - 设置为 8dp

似乎设置卡片高度也会影响视图的尺寸......如果您现在仔细查看图片#1,您会看到,这个按钮也不是一个完美的圆形。

有没有办法解决这个问题?我也尝试设置这个

cardview:cardPreventCornerOverlap="false"

但这也没有影响

多谢你们 :)

4

2 回答 2

1

将 CardView 用于 FAB 阴影并不是最好的主意。CardView 是一个布局,所以它很重。它在棒棒糖之前的版本上也非常有限。阴影没有动画,角落填充内容并且没有波纹。似乎没有什么好方法可以仅使用 AppCompat 来实现 100% FAB。

一般来说,我不喜欢局限于 AppCompat,所以我在常规类的基础上编写了自己的 Button 类。正如您在屏幕截图中看到的那样,我能够取得相当不错的结果。它是 Gingerbread,有动画阴影、涟漪、矢量图形等。这是一个相当大的存储库,所以我无法在这里给你一个简短的解决方案,但如果你愿意,请查看github上的代码。

在此处输入图像描述

于 2015-05-09T09:41:37.320 回答
0

如果您迫切需要旧设备上的阴影效果,您可以尝试使用这个 MaterialDesign 库中的 FAB。

您可以在https://github.com/navasmdc/MaterialDesignLibrary找到该库

<com.gc.materialdesign.views.ButtonFloat
            android:id="@+id/buttonFloat"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_marginRight="24dp"
            android:background="#1E88E5"
            materialdesign:animate="true"
            materialdesign:iconDrawable="@drawable/ic_action_new" />

或者,您可以在 drawables 文件夹中创建自己的阴影资源,并在按钮下方添加形状,如下所示:

<shape android:shape="oval"
 xmlns:android="http://schemas.android.com/apk/res/android">

 <solid android:color="@color/black_alpha"/>
 <corners android:radius="20dip"/>

并创建一个包含按钮和阴影的图层列表资源

<layer-list
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shadow"/>
<item
 android:drawable="@drawable/button"
 android:bottom="4px" />  
 </layer-list>
于 2015-05-05T14:45:49.883 回答