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


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

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

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

null

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>

null

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

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(R.id.iwh_toast_text).text = str
    iwhToast.show()
}

null

这样就好了,注意,设置多个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()
    }

}

null


文章作者: 2winter
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 2winter !
  目录