11package com.catchpig.utils.ext
22
3- import android.graphics.Rect
43import android.view.Gravity
54import android.view.View
5+ import android.view.ViewGroup.MarginLayoutParams
66import android.widget.FrameLayout
77import android.widget.TextView
88import androidx.annotation.ColorRes
@@ -13,17 +13,20 @@ import androidx.core.view.updateLayoutParams
1313import com.catchpig.utils.R
1414import com.google.android.material.snackbar.Snackbar
1515
16- fun View.showSnackBar (text : CharSequence , @DrawableRes background : Int , gravity : Int = Gravity .BOTTOM ) {
16+ fun View.showSnackBar (
17+ text : CharSequence ,
18+ @DrawableRes background : Int ,
19+ gravity : Int = Gravity .BOTTOM
20+ ) {
1721 val snackbar = Snackbar .make(this , text, Snackbar .LENGTH_LONG )
1822 snackbar.setBackgroundResource(background)
1923 snackbar.setTextColorRes(R .color.color_black)
2024 if (gravity == Gravity .BOTTOM ) {
21- val parentView = snackbar.targetParent()
22- val bottom = 20 + context.px2dp((parentView.bottom - bottom) )
23- snackbar.setMargin( 20 , 0 , 20 , bottom)
25+ val layoutParams = snackbar.view.layoutParams as MarginLayoutParams
26+ layoutParams.bottomMargin = dp2px( 20 )
27+ snackbar.view.layoutParams = layoutParams
2428 } else {
2529 snackbar.setGravity(gravity)
26- snackbar.setMargin(20 , 0 , 20 , 0 )
2730 }
2831 snackbar.show()
2932}
@@ -37,12 +40,11 @@ fun View.showSnackBar(
3740 snackbar.setBackgroundResource(background)
3841 snackbar.setTextColorRes(R .color.color_black)
3942 if (gravity == Gravity .BOTTOM ) {
40- val parentView = snackbar.targetParent()
41- val bottom = 20 + context.px2dp((parentView.bottom - bottom) )
42- snackbar.setMargin( 20 , 0 , 20 , bottom)
43+ val layoutParams = snackbar.view.layoutParams as MarginLayoutParams
44+ layoutParams.bottomMargin = dp2px( 20 )
45+ snackbar.view.layoutParams = layoutParams
4346 } else {
4447 snackbar.setGravity(gravity)
45- snackbar.setMargin(20 , 0 , 20 , 0 )
4648 }
4749 snackbar.show()
4850}
@@ -73,30 +75,10 @@ fun Snackbar.setGravity(gravity: Int) {
7375 is FrameLayout .LayoutParams -> {
7476 this .gravity = gravity
7577 }
78+
7679 is CoordinatorLayout .LayoutParams -> {
7780 this .gravity = gravity
7881 }
7982 }
8083 }
81- }
82-
83- fun Snackbar.targetParent (): View {
84- val cls = this ::class .java.superclass
85- val field = cls.getDeclaredField(" targetParent" )
86- field.isAccessible = true
87- return field.get(this ) as View
88- }
89-
90- /* *
91- * 设置外边框
92- */
93- fun Snackbar.setMargin (startDp : Int , topDp : Int , endDp : Int , bottomDp : Int ) {
94- val cls = this ::class .java.superclass
95- val field = cls.getDeclaredField(" originalMargins" )
96- field.isAccessible = true
97- val marginStart = context.dp2px(startDp)
98- val topMargin = context.dp2px(topDp)
99- val marginEnd = context.dp2px(endDp)
100- val bottomMargin = context.dp2px(bottomDp)
101- field.set(this , Rect (marginStart, topMargin, marginEnd, bottomMargin))
10284}
0 commit comments