Kotlin:自定义Toast,设置Toast宽度填充

本文介绍了如何在Kotlin中自定义Toast并使其宽度填充全屏,解决了原生Toast样式简单的问题。关键代码在于设置Gravity为`Gravity.FILL_HORIZONTAL or Gravity.BOTTOM`,并可选择性地使用屏幕宽度来精确控制Toast布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天打算重写一个Toast,原生的太丑了、遇到一些小问题,没少折腾!

下面是预览图:这是一个横向填充的Taost。

XML:这里有个地方注意!这样写是无效的,宽度仍然是内容的宽度。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout

    android:padding="5dp"
    android:orientation="vertical"
    android:background="@color/colorAccent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

        <TextView
            android:background="@color/colorAccent"
            android:id="@+id/iwh_toast_text"
            android:layout_width="match_parent"
            android:text="WD"
            android:textAlignment="center"
            android:textColor="@color/white"
            android:layout_height="wrap_content" />

</LinearLayout>

我们需要在代码里动态设置:

Kotlin:iwhToast.setGravity(Gravity.FILL_HORIZONTAL or Gravity.BOTTOM,0,0)这是关键部分,横向填充。

fun Tos(str:String){
    val iwhToast = Toast.makeText(WdTools.getContext(),str,Toast.LENGTH_SHORT)
    val iwhLyout = LayoutInflater.from(WdTools.getContext()).inflate(R.layout.iwh_toast,null)
    iwhToast.setGravity(Gravity.FILL_HORIZONTAL or Gravity.BOTTOM,0,0)
    iwhToast.view = iwhLyout
    iwhToast.setMargin(0f,0f)
    iwhLyout.findViewById<TextView>(R.id.iwh_toast_text).text = str
    iwhToast.show()
}

这样就好了,注意,设置多个Gravity用“or”在kotlin里这是位运算,java用“|”

解决Toast无法横向填充问题。

如果需要精确控制:使用:

 context.getSystemService(Context.WINDOW_SERVICE)获取屏幕宽度,给自定义的Toast设置

LinearLayout.LayoutParams就可以了。

下面是用apply与with扩展的Toast


/**自定义 Toast
 * @author iwh
 * @param showText 自定义文本
 * @param gravity 自定义位置
 * @param type 风格
 * **/

fun iwhToast(showText: String, gravity: Int = Gravity.BOTTOM, type: Int = R.color.right) {

    val iwhContext = App._context
    val setParame = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
    val iwhText = TextView(iwhContext).apply {
        setTextColor(Color.WHITE)
        textAlignment = TextView.TEXT_ALIGNMENT_CENTER
        setPadding(5, 5, 5, 5)
        layoutParams = setParame

    }
    val iwhLyout = LinearLayout(iwhContext).apply {
        layoutParams = setParame
        setBackgroundResource(type)
        addView(iwhText)
    }
   with( Toast.makeText(App.getContext(), showText, Toast.LENGTH_SHORT)){
        setGravity(Gravity.FILL_HORIZONTAL or gravity, 0, 0)
        view = iwhLyout
        setMargin(0f, 0f)
        iwhText.text = showText
        show()
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值