悬浮按钮FloatingActionButton的使用

使用之前需要添加依赖

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

布局文件如下:

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

    <TextView
        android:text="我是文本"
        android:textSize="40sp"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!--FloatingActionButton是一个悬浮的图片按钮。继承自ImageView所以单击事件都是一样的
        位置可以任意设定,FloatingActionButton默认的底色是theme中的colorAccent
        app:backgroundTint="#56abe4"  修改背景色彩
        app:rippleColor="#33728dff"  点击的时候显示的颜色
        app:elevation="6dp"  //显示的阴影大小
        app:pressedTranslationZ="12dp" //点击时的阴影大小
        在5.x的设备上运行,你会发现一些问题(测试系统5.0):木有阴影
            所以记得设置app:borderWidth="0dp",然后再设置一个合理的margin解决出现矩形边框问题-->
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/floatingActioButon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom = "true"
        android:layout_alignParentRight = "true"
        android:layout_margin="20dp"
        app:borderWidth="0dp"
        app:backgroundTint="#56abe4"
        app:rippleColor="#ff0000"
        app:elevation="12dp"
        app:pressedTranslationZ="12dp"
        android:src="@mipmap/ic_launcher"/>

</RelativeLayout>

把它当做ImageView使用就行了,

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

/**
 * 用android.support.v7.widget.Toolbar替换ActionBar,所以需要隐藏原有的标题头:
        方法1.设置App主题为:Theme.AppCompat.Light.NoActionBar
        方法2. supportRequestWindowFeature(Window.FEATURE_NO_TITLE)去掉了默认的导航栏(如果是继承了AppCompatActivity的,
               如果是继承Activity就应该调用 requestWindowFeature(Window.FEATURE_NO_TITLE) )
 */
public class MainActivity extends AppCompatActivity {

    /**
     * 导航栏布局对象,包括布局头与菜单项,左侧侧滑的内容
     */
    private FloatingActionButton floatingActioButon;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去掉默认的导航栏
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        //找到悬浮图片按钮
        floatingActioButon = (FloatingActionButton) findViewById(R.id.floatingActioButon);
        floatingActioButon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "点击了悬浮图片", Toast.LENGTH_SHORT).show();
            }
        });

    }

}

效果图:  点击旁边有浅灰色

posted @ 2016-10-07 10:01  ts-android  阅读(867)  评论(0编辑  收藏  举报