java安卓好看自定义toast_自定义Toast

自定义Toast

平时一般只用默认的Toast,使用Toast.makeTest()方法调用,默认的风格是白字半透明灰框,经常与app的主题颜色不符,所以需要自定义Toast.效果图:

617a8d4aa7fb9cf245099c9b008e141d.png

显示定义需要的布局文件:layout/custom_toast.xml

android:id="@+id/custom_toast_container"

android:orientation="horizontal"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:padding="8dp"

android:background="#DAAA"

>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginRight="8dp"

/>

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textColor="#FFF"

/>

注意root view 的I必须设置id(接下来代码用到,此时为custom_toast_container)

接下来是kotlin代码(根据android官网,手动将Java代码改为Kotliin代码)

class ToastActivity:AppCompatActivity(){

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

var layoutInflater:LayoutInflater = layoutInflater

//这里需要一个安全类型转换as?, 不然编译无法通过,因为ViewGroup是not null类型,

//而findViewById(R.id.custom_toast_container)可能为null,所以不能直接用as

var layout: View = layoutInflater.inflate(R.layout

.custom_toast, findViewById(R.id.custom_toast_container) as? ViewGroup)

val text:TextView = layout.findViewById(R.id.text) as TextView

text.setText("This is a custom toast")

//这个如果是java语法,则需要调用getApplicationContext,

val toast = Toast(applicationContext)

toast.setGravity(Gravity.CENTER_VERTICAL, 0, 300)//设置位置

toast.duration = Toast.LENGTH_LONG

toast.view = layout//java:toast.setView(layout);

toast.show()

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值