最近做东西,发现要用floatActionButton浮动按钮。废话不多说,上书写方法。
One,build.gradle(app)->dependencies加一句:
compile 'com.android.support:design:24.2.0',并且sync now
/*此处备注:该design的版本必须和targetsdkversion的版本相同,如果不同,则无法完成引入*/
Two,进入主界面修改layout文件
引入:
xmlns:app="http://schemas.android.com/apk/res-auto"
<android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="16dp" android:src="@drawable/btn_float" app:backgroundTint="?android:attr/colorPressedHighlight" />
/*说明一下:如果floatActionButton与listview,recyclerview同用,需要浮在view的上面,不遮挡其内容,需要用到framelayout(覆盖式布局)*/
上面是第一种方法,现在是第二种方法。
one,如上第一步。
two,布局
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:fab="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <!--这里FrameLayout布局是覆盖式布局--> <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/recycler_view" android:paddingTop="15dp" /> <com.melnykov.fab.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="20dp" android:src="@drawable/btn_float" android:scaleType="centerInside" fab:fab_type="normal" fab:fab_shadow="true" fab:fab_colorNormal="@color/colorPrimary" fab:fab_colorPressed="@color/colorPrimary" fab:fab_colorRipple="@color/colorAccent" android:backgroundTint="@android:color/holo_orange_light" /> </FrameLayout>
three,在所要引入界面的activity中手动导包:
import com.melnykov.fab.FloatingActionButton;
four,实现view和floatactionbutton的动画,即类似于知乎app上的效果,则
//fab附着在listview上,跟随recyclervie滚动 FloatingActionButton fab=(FloatingActionButton) view.findViewById(R.id.fab); fab.attachToRecyclerView(recyclerview); fab.setColorPressed(0xffb71c1c); return view;
第二种实现起来更加简单,第一种通过动画也可以实现,这里只实现了更简单的方法。