高級UI-FloatingActionButton


FloatingActionButton為懸浮按鈕,就是常見的那種懸浮在控件上,可以調出其他菜單的按鈕

FloatingActionButton的特有屬性

app:backgroundTint 按鈕的背景顏色
app:backgroundTintMode 按鈕背景顏色的模式
app:borderWidth 該屬性如果不設置0dp,那么在4.x的sdk上FAB會顯示為正方形,而且在5.0以后的sdk沒有陰影效果。所以設置為borderWidth="0dp",同時設置4.x:android:layout_margin="16dp",5.0以上android:layout_margin="0dp"
app:elevation 默認狀態下陰影大小
app:fabSize 設置大小,該屬性有兩個值,分別為normal和mini,對應的大小分別為56dp和40dp
app:pressedTranslationZ 按鈕按下去的狀態下的陰影大小
app:rippleColor 設置點擊時的背景顏色
app:useCompatPadding 是否使用兼容的填充大小

FloatingActionButton的使用

首先依舊是引入依賴

implementation 'com.android.support:design:25.4.0'

其實際上是繼承了ImageButton,故和ImageButton的使用方式類似

<?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

    <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:onClick="changeDire" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_margin="16dp" android:clickable="true" android:src="@android:drawable/ic_input_add" app:backgroundTint="@android:color/holo_purple" app:borderWidth="3dp" app:elevation="16dp" app:rippleColor="@color/colorPrimary" />

</RelativeLayout>

順便實現中間的 + 旋轉功能

public class MainActivity extends AppCompatActivity {

    private boolean reverse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void changeDire(View view) {
        Float toDegree = reverse ? -45.0F : 0F;
        ObjectAnimator animator = ObjectAnimator
                .ofFloat(view, "rotation", 0.0F, toDegree)
                .setDuration(300);
        animator.start();
        reverse = !reverse;
    }
}

實現FAB的顯示和隱藏

模擬實現

這里使用一個ImageButton來模擬FAB,完成其效果
因為要模擬FAB,需要一個陰影效果

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@android:color/darker_gray"/>
        </shape>
    </item>
    <item android:bottom="3dp">
        <shape android:shape="oval">
            <solid android:color="@color/colorPrimaryDark"/>
        </shape>
    </item>
</layer-list>

將布局實現出來

<?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" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:clipChildren="false" android:clipToPadding="false" android:paddingTop="?attr/actionBarSize" />

    <android.support.v7.widget.Toolbar android:id="@+id/tool_bar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" />

    <ImageButton android:id="@+id/image_button" android:layout_width="58dp" android:layout_height="58dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_margin="16dp" android:background="@drawable/image_button_bg" android:src="@android:drawable/ic_input_add" />

</RelativeLayout>

編寫適配器,直接使用系統資源

public class FABAdapter extends RecyclerView.Adapter<FABAdapter.MyViewHolder> {
    private List<String> list;

    class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView textView;

        public MyViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewById(android.R.id.text1);
        }
    }

    public FABAdapter(List<String> list) {
        this.list = list;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(android.R.layout.simple_list_item_1,parent,false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.textView.setText(list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}

設置滑動簡體

public class FABScrollListener extends RecyclerView.OnScrollListener {

    private static final int THRESHOLD = 20;
    private ShowScrollListener showScrollListener;
    private int distence = 0;
    private boolean isShow;

    public FABScrollListener(ShowScrollListener showScrollListener) {
        this.showScrollListener = showScrollListener;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        //x,y方向的增量
        if (distence > THRESHOLD && isShow) {
            //隱藏動畫
            isShow = false;
            showScrollListener.onHide();
            distence = 0;
        } else if (distence < -20 && !isShow) {
            //顯示動畫
            isShow = true;
            showScrollListener.onShow();
            distence = 0;
        }
        if ((isShow && dy > 0) || (!isShow && dy < 0)) {
            distence += dy;
        }
    }
}

設置回調接口

public interface ShowScrollListener {
    void onShow();
    void onHide();
}

實現回調接口,使用屬性動畫完成其邏輯

public class MainActivity extends AppCompatActivity implements ShowScrollListener {

    private List<String> list = new ArrayList<>();
    ;
    private RecyclerView recyclerView;
    private Toolbar toolbar;
    private ImageButton imageButton;
    private FABAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        imageButton = (ImageButton) findViewById(R.id.image_button);
        setSupportActionBar(toolbar);
        setTitle("這是標題");
        recyclerView.addOnScrollListener(new FABScrollListener(this));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        for (int i = 0; i < 30; i++) {
            list.add("item " + i);
        }
        adapter = new FABAdapter(list);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onHide() {
        LayoutParams params = (LayoutParams) imageButton.getLayoutParams();
        toolbar.animate().translationY(-toolbar.getHeight()).
                setInterpolator(new AccelerateInterpolator(1F));
        imageButton.animate().translationY(imageButton.getHeight() + params.bottomMargin)
                .setInterpolator(new AccelerateInterpolator(1F));
    }

    @Override
    public void onShow() {
        toolbar.animate().translationY(0)
                .setInterpolator(new DecelerateInterpolator(1F));
        imageButton.animate().translationY(0)
                .setInterpolator(new DecelerateInterpolator(1F));
    }
}

由於使用到了Toolbar,所以主題樣式應設置為NoActionBar

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style>

</resources>

效果如下
FloatingActionButton-FAB顯隱

使用CoordinatorLayout實現

主要是使用RecyclerView + FloatingActionButton + CoordinatorLayoutCoordinatorLayout的作用是協調並調度子空間及布局來實現觸摸(滑動)產生的動畫效果,使用View的Behavior來實現觸摸的動畫調度
由於CoordinatorLayout位於support-design,所以需要導入

implementation 'com.android.support:recyclerview-v7:25.4.0'
implementation 'com.android.support:design:25.4.0'

然后修改其布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:clipChildren="false" android:clipToPadding="false" android:paddingTop="?attr/actionBarSize" />

    <android.support.v7.widget.Toolbar android:id="@+id/tool_bar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" />

    <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right|bottom" android:layout_margin="16dp" android:src="@android:drawable/ic_input_add" app:layout_behavior=".FABBehavivor" />

</android.support.design.widget.CoordinatorLayout>

適配器保持不變

package com.cj5785.fabshowandhidebehavivor;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class FABAdapter extends RecyclerView.Adapter<FABAdapter.MyViewHolder> {
    private List<String> list;

    class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView textView;

        public MyViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewById(android.R.id.text1);
        }
    }

    public FABAdapter(List<String> list) {
        this.list = list;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(android.R.layout.simple_list_item_1,parent,false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.textView.setText(list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}

實現Behavivor

package com.cj5785.fabshowandhidebehavivor;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;

public class FABBehavivor extends FloatingActionButton.Behavior {

    private boolean isShow;

    public FABBehavivor(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    //依賴滑動開始回調
    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child, View directTargetChild, View target, int nestedScrollAxes) {
        //nestedScrollAxes 滑動的方向,這里我們依賴recyclerview,只關心其是否垂直滑動
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL
                || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, nestedScrollAxes);
    }

    //依賴滑動過程回調
    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout, FloatingActionButton child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
        //根據情況執行動畫
        if (dyConsumed > 0 && isShow) {
            isShow = false;
            onHide(child);
        } else if (dyConsumed < 0) {
            isShow = true;
            onShow(child);
        }
    }

    private void onShow(FloatingActionButton fab) {
        ViewCompat.animate(fab).scaleX(1f).scaleY(1f).start();
    }

    private void onHide(FloatingActionButton fab) {
        ViewCompat.animate(fab).scaleX(0f).scaleY(0f).start();
    }
}

調用里面就沒那么多監聽了

public class MainActivity extends AppCompatActivity{

    private List<String> list = new ArrayList<>();
    private RecyclerView recyclerView;
    private Toolbar toolbar;
    private FloatingActionButton fab;
    private FABAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        setSupportActionBar(toolbar);
        setTitle("這是標題");
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        for (int i = 0; i < 30; i++) {
            list.add("item " + i);
        }
        adapter = new FABAdapter(list);
        recyclerView.setAdapter(adapter);
    }
}

效果如下
FloatingActionButton-FAB顯隱Behavivor


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM