如何使SnackBar不匹配_parent - androidKotlin

yi0zb3m4  于 2023-08-01  发布在  Android
关注(0)|答案(1)|浏览(55)

最初,我想用自定义布局来制作Toast,但后来我发现从Android 11开始,这样做是不可取的,ToastsetView()方法变成了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 SnackBarKotlin函数:

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,但使用各种方法我都无法做到这一点。有什么解决办法吗?
在我的手机上看起来如何:

的数据
它应该是什么样子:

whlutmcx

whlutmcx1#

你应该试试吐司。简单得多,符合您的要求。
如果你仍然想让你的SnackBar不匹配父节点,你可以尝试像这样编程添加layoutParams:
第一个月
layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
snackbarLayout.layoutParams = layoutParams
我希望它工作!

相关问题