最初,我想用自定义布局来制作Toast
,但后来我发现从Android 11
开始,这样做是不可取的,Toast
的setView()
方法变成了deprecated
。我决定尝试做同样的事情,但只针对Snackbar
。
我的自定义Snackbar
的xml代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardBackgroundColor="@color/blue"
app:cardCornerRadius="20dp"
app:contentPaddingBottom="4dp"
app:contentPaddingLeft="12dp"
app:contentPaddingRight="12dp"
app:contentPaddingTop="4dp">
<com.google.android.material.textview.MaterialTextView
android:id="@+id/text_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableEnd="@drawable/ic_vector_check_mark_white"
android:drawablePadding="4dp"
android:fontFamily="@font/tt_hoves_medium"
android:text="Copied"
android:textAlignment="center"
android:textColor="@color/white"
android:textSize="10sp" />
</androidx.cardview.widget.CardView>
字符串
用于show SnackBar
的Kotlin
函数:
private fun showSnack() {
val snackbar = Snackbar.make(binding.root, "", Snackbar.LENGTH_SHORT)
snackbar.view.setBackgroundColor(Color.TRANSPARENT)
val customSnackView: View = layoutInflater.inflate(R.layout.component_toast_message, null)
val snackbarLayout = snackbar.view as Snackbar.SnackbarLayout
snackbarLayout.setPadding(0, 0, 0, 0)
snackbarLayout.addView(customSnackView)
snackbar.show()
}
型
然而,我遇到了一个问题,我的Snackbar
有一个match_parant
的宽度,虽然我需要它有View
本身的大小,也就是wrap_content
,但使用各种方法我都无法做到这一点。有什么解决办法吗?
在我的手机上看起来如何:
的数据
它应该是什么样子:
的
1条答案
按热度按时间whlutmcx1#
你应该试试吐司。简单得多,符合您的要求。
如果你仍然想让你的SnackBar不匹配父节点,你可以尝试像这样编程添加layoutParams:
第一个月
layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
个snackbarLayout.layoutParams = layoutParams
个我希望它工作!