前幾天看到一片文章,文章的標題是Android 仿美團拖拽效果,抱著好奇心去看了下,效果確實不錯,但實現過程較為復雜。用原生的CoordinatorLayout+BottomSheetBehavior可以快速的實現這一效果,所以心血來潮打算水一篇文章。
demo地址:https://github.com/weibindev/BottomSlide
注:
本文demo的所有圖文素材均來自http://www.lxweimin.com/p/92180b45aaf7
先來看下成品效果:
實現思路分析:
- 界面上可以分為兩個部分:頂部部分包括一系列的圖片和按鈕控件;底部部分是用
NestedScrollView
包裹實現的界面,并且指定app:layout_behavior="@string/bottom_sheet_behavior"
。界面根布局采用CoordinatorLayout
,與BottomSheetBehavior
包裝底部部分的布局實現拖拽。 - 當界面初始化時,
BottomSheetBehavior
以淡入的方式平滑至設定的最小高度。在BottomSheetBehavior
拖拽過程中,通過代碼改變View的layoutParams
屬性使其達到所能拖拽的最大高度。 - 除去底部部分初始化淡入的過程,其余時間頂部部分都會發生色差值和視圖偏移的變化。
界面布局:
activity_main.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="@layout/include_main_top"/>
<include layout="@layout/include_main_content"/>
</android.support.design.widget.CoordinatorLayout>
include_main_top.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/constraint"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="350dp"
android:scaleType="centerCrop"
android:src="@mipmap/icon_tour_background"
android:transitionName="cardView"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="25dp"
android:padding="10dp"
android:src="@mipmap/icon_back_white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="25dp"
android:padding="10dp"
android:src="@mipmap/icon_tour_forward"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<ImageView
android:id="@+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="25dp"
android:padding="10dp"
android:src="@mipmap/icon_tour_loved"
app:layout_constraintEnd_toStartOf="@+id/imageView2"
app:layout_constraintTop_toTopOf="parent"/>
<!--這里為了方便,使用半透明色遮罩的方式來代替色差值的實現-->
<View
android:id="@+id/maskView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="0"
android:background="#80000000"/>
</android.support.constraint.ConstraintLayout>
include_main_content.xml
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_cardview_white_top"
app:layout_behavior="@string/bottom_sheet_behavior"
android:overScrollMode="never">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="16dp"
android:paddingEnd="16dp">
<android.support.v7.widget.CardView
android:id="@+id/cardView"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_margin="20dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:foreground="?attr/selectableItemBackground"
app:cardCornerRadius="25dp"
app:cardElevation="1dp"
app:layout_constraintBottom_toBottomOf="@+id/view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/textView">
<ImageView
android:id="@+id/avatar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#59cebe"
android:transitionName="avatar"/>
</android.support.v7.widget.CardView>
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
android:text="一種色彩一座城,多彩摩洛哥自由行、慢行、心靈之旅"
android:textColor="@color/black"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constrainedWidth="true"
app:layout_constraintEnd_toStartOf="@id/cardView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:alpha="0.8"
android:drawableStart="@mipmap/icon_tour_location"
android:drawablePadding="4dp"
android:text="摩洛哥"
android:textColor="@color/black"
android:textSize="12sp"
app:layout_constraintTop_toBottomOf="@id/textView"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:alpha="0.8"
android:drawableStart="@mipmap/icon_tour_map"
android:drawablePadding="4dp"
android:text="線路玩法"
android:textColor="@color/black"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="@+id/textView1"
app:layout_constraintStart_toEndOf="@+id/textView1"
app:layout_constraintTop_toTopOf="@+id/textView1"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:drawableStart="@mipmap/icon_tour_label"
android:drawablePadding="4dp"
android:text="心靈之旅"
android:textColor="@color/gray"
android:textSize="10sp"
app:layout_constraintTop_toBottomOf="@+id/textView1"/>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:alpha="0.8"
android:drawableStart="@mipmap/icon_tour_label"
android:drawablePadding="4dp"
android:text="古城"
android:textColor="@color/gray"
android:textSize="10sp"
app:layout_constraintBottom_toBottomOf="@+id/textView3"
app:layout_constraintStart_toEndOf="@+id/textView3"
app:layout_constraintTop_toTopOf="@+id/textView3"/>
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:alpha="0.8"
android:drawableStart="@mipmap/icon_tour_label"
android:drawablePadding="4dp"
android:text="清真寺"
android:textColor="@color/gray"
android:textSize="10sp"
app:layout_constraintBottom_toBottomOf="@+id/textView3"
app:layout_constraintStart_toEndOf="@+id/textView4"
app:layout_constraintTop_toTopOf="@+id/textView3"/>
<View
android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_marginTop="10dp"
android:background="@color/background"
app:layout_constraintTop_toBottomOf="@+id/textView3"/>
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="行程詳情"
android:textColor="@color/black"
android:textSize="12sp"
app:layout_constraintTop_toBottomOf="@+id/view"/>
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
android:src="@mipmap/icon_tour_background"
app:layout_constraintTop_toBottomOf="@+id/textView6"/>
<TextView
android:id="@+id/textView7"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="It was a humorously peritous business for both of us.For, before we proceed further,it must be said that the mokey-rope was fast at both ends.fast to Queequeg's broad canvas belt,and fast to my narrow leather one,So tat for better or for worse.所以說這是一場凈化心靈之旅"
android:textColor="@color/black"
android:textSize="12sp"
app:layout_constrainedWidth="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView1"/>
<View
android:id="@+id/view2"
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_marginTop="8dp"
android:background="@color/background"
app:layout_constraintTop_toBottomOf="@+id/textView7"/>
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/view2"
app:tabIndicatorColor="@color/yellow"
app:tabIndicatorHeight="2dp"
app:tabMaxWidth="80dp"
app:tabMinWidth="50dp"
app:tabPadding="-1dp"
app:tabSelectedTextColor="@color/black"
app:tabTextColor="@color/gray"/>
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="420dp"
android:layout_marginTop="5dp"
android:background="#aabbcc"
app:layout_constraintTop_toBottomOf="@+id/tabLayout"/>
</android.support.constraint.ConstraintLayout>
</android.support.v4.widget.NestedScrollView>
在<android.support.v4.widget.NestedScrollView
中加入了app:layout_behavior="@string/bottom_sheet_behavior"
。除此之外,還有三個關于BottomSheetBehavior
相關的xml屬性:
app:behavior_hideable 設置此底部工作表在向下滑動時是否可以隱藏。
app:behavior_peekHeight 設置折疊時底部工作表的高度
app:behavior_skipCollapsed 設置此底部工作表在展開一次后是否應在隱藏時跳過折疊狀態。除非工作表可隱藏,否則將此設置為true無效。
順便附上BottomSheetBehavior
的5種狀態:
STATE_COLLAPSED:底部頁面折疊。
STATE_EXPANDED:底部頁面擴展。
STATE_DRAGGING:底部是拖動。
STATE_SETTLING:底層正在沉淀。
STATE_HIDDEN:底部頁面是隱藏的。
更多關于BottomSheetBehavior的介紹,可以前往官方文檔查看:https://developer.android.com/reference/android/support/design/widget/BottomSheetBehavior
代碼實現:
假設為了適配不同的機型,我們需要把底部布局的最小高度設為屏高的一半,所以初始化控件之前,先初始化相關高度的參數
//獲取屏幕高度
heightPixels = resources.displayMetrics.heightPixels
Log.i(TAG, "heightPixels: $heightPixels")
val behaviorHeight = DensityUtils.px2dp(this, (heightPixels / 2).toFloat())
peekHeight =TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, behaviorHeight, resources.displayMetrics).toInt()
Log.i(TAG, "peekHeight: $peekHeight")
最小高度已經搞定了,使用setPeekHeight
生效。那么最大高度該如何實現呢,我查看文檔,發現api并沒有提供相關的函數來實現這一功能。這樣的話,我們可以改變布局控件自身的高度來實現,也就是layoutParams.heigth。
說是這么說,我們還是得取一個參照物的高度值套進layoutParams.heigth
。這里我就采用返回按鈕做為參照物,即底部的最大高度不遮擋返回按鈕。
imageView.post {
val lp = imageView.layoutParams as ConstraintLayout.LayoutParams
//獲取狀態欄高度
var statusBarHeight = 0
val resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
statusBarHeight = resources.getDimensionPixelSize(resourceId)
}
//返回按鈕至屏幕頂部的高度
marginTop = imageView.height + lp.topMargin + lp.bottomMargin / 2 + statusBarHeight
//返回按鈕至根布局的距離
offsetDistance = lp.topMargin
}
獲取到marginTop
后在BottomSheetBehavior.BottomSheetCallback()
回調監聽有底部工作的事件。
BottomSheetBehavior.BottomSheetCallback()
有兩個事件
//在拖動時調用
void onSlide (View bottomSheet, float slideOffset)
//在改變狀態時調用
void onStateChanged (View bottomSheet, int newState)
只要底部進行拖拽,其狀態就會發生變化,所以在onStateChanged (View bottomSheet, int newState)
做處理
behavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(bottomSheet: View, newState: Int) {
val layoutParams = bottomSheet.layoutParams
//如果控件本身的Height值就小于返回按鈕的高度,就不用做處理
if (bottomSheet.height > heightPixels - marginTop) {
//屏幕高度減去marinTop作為控件的Height
layoutParams.height = heightPixels - marginTop
bottomSheet.layoutParams = layoutParams
}
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {
}
})
相應的頂部色差值和偏移值的變化在另一個回調事件void onSlide (View bottomSheet, float slideOffset)
中處理。
behavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(bottomSheet: View, newState: Int) {
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {
var distance: Float = 0F;
/**
* slideOffset為底部的新偏移量,值在[-1,1]范圍內。當BottomSheetBehavior處于折疊(STATE_COLLAPSED)和
* 展開(STATE_EXPANDED)狀態之間時,它的值始終在[0,1]范圍內,向上移動趨近于1,向下區間于0。[-1,0]處于
* 隱藏狀態(STATE_HIDDEN)和折疊狀態(STATE_COLLAPSED)之間。
*/
//這里的BottomSheetBehavior初始化完成后,界面設置始終可見,所以不用考慮[-1,0]區間
//色差值變化->其實是遮罩的透明度變化,拖拽至最高,頂部成半透明色
maskView.alpha = slideOffset
//offsetDistance是initSystem()中獲得的,是返回按鈕至根布局的距離
distance = offsetDistance * slideOffset
//當BottomSheetBehavior由隱藏狀態變為折疊狀態(即gif圖開始的由底部滑出至設置的最小高度)
//slide在[-1,0]的區間內,不加判斷會出現頂部布局向下偏移的情況。
if (distance > 0) {
constraint.translationY = -distance
}
}
})
最后還有BottomSheetBehavior
的滑出效果:先設置BottomSheetBehavior
的狀態為隱藏,然后調用Handler
的postDelayed()
方法設置狀態為折疊以及最小高度,當然再加一個屬性動畫,起到錦上添花的作用。
附上MainActivity.kt
的全部代碼
/**
* @author vico
* @date 2019/1/23
* email: 1005078384@qq.com
*/
class MainActivity : AppCompatActivity() {
private var heightPixels: Int = 0
private var peekHeight: Int = 0
private var marginTop: Int = 0
private var offsetDistance: Int = 0
private lateinit var mHandler: Handler
companion object {
const val TAG = "MainActivity.class"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//初始屏幕相關的參數
initSystem()
initView()
initBehavior()
}
private fun initBehavior() {
val behavior = BottomSheetBehavior.from(nestedScrollView)
behavior.isHideable = true
behavior.state = BottomSheetBehavior.STATE_HIDDEN
behavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(bottomSheet: View, newState: Int) {
val layoutParams = bottomSheet.layoutParams
//如果控件本身的Height值就小于返回按鈕的高度,就不用做處理
if (bottomSheet.height > heightPixels - marginTop) {
//屏幕高度減去marinTop作為控件的Height
layoutParams.height = heightPixels - marginTop
bottomSheet.layoutParams = layoutParams
}
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {
var distance: Float = 0F;
/**
* slideOffset為底部的新偏移量,值在[-1,1]范圍內。當BottomSheetBehavior處于折疊(STATE_COLLAPSED)和
* 展開(STATE_EXPANDED)狀態之間時,它的值始終在[0,1]范圍內,向上移動趨近于1,向下區間于0。[-1,0]處于
* 隱藏狀態(STATE_HIDDEN)和折疊狀態(STATE_COLLAPSED)之間。
*/
//這里的BottomSheetBehavior初始化完成后,界面設置始終可見,所以不用考慮[-1,0]區間
//色差值變化->其實是遮罩的透明度變化,拖拽至最高,頂部成半透明色
maskView.alpha = slideOffset
//offsetDistance是initSystem()中獲得的,是返回按鈕至根布局的距離
distance = offsetDistance * slideOffset
//當BottomSheetBehavior由隱藏狀態變為折疊狀態(即gif圖開始的由底部滑出至設置的最小高度)
//slide在[-1,0]的區間內,不加判斷會出現頂部布局向下偏移的情況。
if (distance > 0) {
constraint.translationY = -distance
}
Log.i(
TAG,
String.format(
"slideOffset -->>> %s bottomSheet.getHeight() -->>> %s heightPixels -->>> %s",
slideOffset,
bottomSheet.height,
heightPixels
)
)
Log.i(TAG, String.format("distance -->>> %s", distance))
}
})
mHandler.postDelayed({
behavior.isHideable = false
behavior.state = BottomSheetBehavior.STATE_COLLAPSED
behavior.peekHeight = peekHeight
ObjectAnimator.ofFloat(nestedScrollView, "alpha", 0f, 1f).setDuration(500).start()
}, 200)
}
private fun initView() {
tabLayout.tabMode = TabLayout.MODE_SCROLLABLE
tabLayout.addTab(tabLayout.newTab().setText("費用說明"))
tabLayout.addTab(tabLayout.newTab().setText("預定須知"))
tabLayout.addTab(tabLayout.newTab().setText("退款政策"))
tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabReselected(tab: TabLayout.Tab) {
}
override fun onTabUnselected(tab: TabLayout.Tab) {
}
override fun onTabSelected(tab: TabLayout.Tab) {
when (tab.position) {
0 -> frameLayout.setBackgroundColor(Color.parseColor("#ff0000"))
1 -> frameLayout.setBackgroundColor(Color.parseColor("#0000ff"))
2 -> frameLayout.setBackgroundColor(Color.parseColor("#00ff00"))
}
}
})
imageView.setOnClickListener { finish() }
imageView2.setOnClickListener { Toast.makeText(this, "轉發", Toast.LENGTH_SHORT).show() }
imageView3.setOnClickListener { Toast.makeText(this, "收藏", Toast.LENGTH_SHORT).show() }
mHandler = Handler()
}
private fun initSystem() {
//獲取屏幕高度
heightPixels = resources.displayMetrics.heightPixels
Log.i(TAG, "heightPixels: $heightPixels")
val behaviorHeight = DensityUtils.px2dp(this, (heightPixels / 2).toFloat())
peekHeight =
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, behaviorHeight, resources.displayMetrics).toInt()
Log.i(TAG, "peekHeight: $peekHeight")
imageView.post {
val lp = imageView.layoutParams as ConstraintLayout.LayoutParams
//獲取狀態欄高度
var statusBarHeight = 0
val resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android")
if (resourceId > 0) {
statusBarHeight = resources.getDimensionPixelSize(resourceId)
}
//返回按鈕至屏幕頂部的高度
marginTop = imageView.height + lp.topMargin + lp.bottomMargin / 2 + statusBarHeight
//返回按鈕至根布局的距離
offsetDistance = lp.topMargin
}
}
}
最后:
文章demo地址:https://github.com/weibindev/BottomSlide
demo引用素材:
Android 仿美團拖拽效果
參考文章:
Material Design系列-嚴振杰