越简短,越实用
在目前的认知中,可能实现悬浮框的方式有俩种
- 使用
ImageView+RelativeLayout进行实现,不过无动画,无阴影(注意:在Activity或Fragment中,业务尝尝要求动态显示和隐藏,所以我们需要在对用的生命周日内进行设置,如onPause的时候让ImageView消失,反之在onStart或者onResume中显示) - 使用这篇文章中的
FloatActionButton,设通过属性设置阴影等状态(就从现在学习这种5.0的悬浮框吧)
Effect :
bulid中添加(5.0特性之一,25.2.0对应自己使用的SDK):
compile 'com.android.support:design:25.2.0'
xml中添加(为了调用自定义属性):
xmlns:app="http://schemas.android.com/apk/res-auto"
调用控件名称:
<android.support.design.widget.FloatingActionButton/>
建议:
最外层布局最好使用RelativeLayout,之后使用Buttom和Center的属性,因为我使用LinearLayout的buttom属性有时候无效(当然也可能是我的问题,所以纯属建议)
自定义属性介绍(下面的数值由自己设置):
一般状态时候的背景颜色
app:backgroundTint="#fff"
点击状态时候的背景颜色
app:rippleColor="#33728dff"
一般状态时候的阴影大小
android:elevation="18dp"
点击状态时候的阴影大小
app:pressedTranslationZ="26dp"
MainActivity
package com.example.dow.floatingactionbutton;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FloatingActionButton mBtn = (FloatingActionButton) findViewById(R.id.floatingActionButton);
mBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"触发浮标点击",Toast.LENGTH_SHORT).show();
}
});
}
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dow.floatingactionbutton.MainActivity">
<android.support.design.widget.FloatingActionButton
android:id="@+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
app:backgroundTint="#fff"
app:rippleColor="#33728dff"
app:elevation="18dp"
app:pressedTranslationZ="26dp"
android:layout_marginBottom="30dp"
/>
</RelativeLayout>