android悬浮按钮的使用

 

首先准备一张图片保存在drawable下

在activity_main.xml下

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/draw_lay"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <android.support.v7.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.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            />
        <!--下面是悬浮按钮-->
        <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/done"
            app:elevation="8dp"/><!--设置高度值-->
    </FrameLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/navmenu"
        app:headerLayout="@layout/navhead"/>

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

在MainActivity中添加响应事件

在下面代码中使用了SnackBar,这个控件可以弹出一个可与用户交互的消息,创建SnackBar三个参数分别是:view,内容,时长

 FloatingActionButton fab=(FloatingActionButton)findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(v,"你点击了悬浮按钮",Snackbar.LENGTH_SHORT).setAction("Undo",new View.OnClickListener(){
                    @Override
                    public void onClick(View v){
                        Toast.makeText(MainActivity.this,"你点击了悬浮按钮中的Undo按钮",Toast.LENGTH_SHORT).show();
                    }

                }).show();

在这种情况下SnackBar弹出的内容就会自动挡住悬浮按钮,此时我们将xml布局中的FrameLayout改为<android.support.design.widget.CoordinatorLayout

这是Material Design中提供一种布局在平常情况下与FrameLayout差异不大,但是他可以监控所有子控件的事件,然后为我们做出合理的相应

 

posted @ 2019-03-30 17:18  王怀宇  阅读(445)  评论(0编辑  收藏  举报