如何在Android中创建一个浮动的操作按钮(FAB),利用AppCompat V21?

如何在Android中创建一个浮动的操作按钮(FAB),利用AppCompat V21?

问题描述:

我想创建一个浮动的操作按钮(为项目添加到列表视图),像谷歌日历,保持(5.0前)与pre-棒棒糖的Andr​​oid版本兼容。

I would like to create a floating action button (to add items to a listview), like google calendar, maintaining compatibility with pre-lollipop Android versions (before 5.0).

我创造了这个布局:

活动main_activity.xml:

Activity main_activity.xml:

<LinearLayout ... >

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

     <RelativeLayout ... >

     <!-- My rest of the layout -->

          <!-- Floating action button -->
          <ImageButton style="@style/AppTheme"
                     android:layout_width="60dp"
                     android:layout_height="60dp"
                     android:text="New Button"
                     android:id="@+id/button"
                     android:src="@drawable/ic_fab"
                     android:background="@drawable/fab"
                     android:layout_alignParentBottom="true"
                     android:layout_alignParentRight="true"
                     android:layout_marginBottom="24dp"
                     android:layout_marginRight="24dp"/>

     </RelativeLayout>

 </LinearLayout>

绘制对象fab.xml:

Drawable fab.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">
    <solid android:color="#ffa48bc0"/>
</shape>

风格styles.xml

Style styles.xml

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">#ff1d79b1</item>
        <item name="colorPrimaryDark">#ff084d95</item>
    </style>
</resources>

的结果是相似的,但有不遮光,材料设计的一个特点:

The result is similar, but there isn't the shading, a characteristic of material design:

日历的浮动操作按钮:

我的应用程序的浮点操作按钮:

My app's floating action button:

我怎样才能阴影添加到我的按钮?

How can I add the shading to my button?

我已经使用的属性提升,但不工作

I have already used the attribute elevation, but does not work

不再有需要创建自己的FAB,也没有使用第三方库,它被列入AppCompat 22。

There is no longer a need for creating your own FAB nor using a third party library, it was included in AppCompat 22.

https://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html

只需添加一个名为设计新的支持库在你的摇篮文件:

Just add the new support library called design in in your gradle-file:

compile 'com.android.support:design:22.2.0'

......,你是好去:

...and you are good to go:

<android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_margin="16dp"
        android:clickable="true"
        android:src="@drawable/ic_happy_image" />