【安卓】界面开发1:Toast


官网链接: https://developer.android.google.cn/guide/topics/ui/notifiers/toasts
声明:以下代码完全是官网摘抄!

1.一句话简单使用:

    Toast.makeText(this, "需要提示的字符串信息", Toast.短或长).show();
   // 没什么好说的,前面的部分是实例化一个对象,最后调用对象的show()方法显示出来。

2.高级定制:xml静态+代码动态

0.熟悉一个方法,下面要用:定制位置:

    toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
    //第一个位置参数:布局对齐方式(如上:上TOP左LEFT对齐)
    //第二第三参数:添加坐标 x,y,让它更符合你的设定

1.xml:文件名——>layout/custom_toast.xml
必须为线性布局设置id,因为我们还要在代码中设定:
看到如下代码,你的头脑应该浮现一根水平线,线上先后排序一张图片和一个文本。

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  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"
                  >
        <ImageView android:src="@drawable/droid"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   android:layout_marginRight="8dp"
                   />
        <TextView android:id="@+id/text"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textColor="#FFF"
                  />
    </LinearLayout>
    

2.代码中设定:
java:

	//获取当前环境下的LayoutInflater对象
    LayoutInflater inflater = getLayoutInflater();
    //使用上面获取到的对象的inflate方法获取View对象
    View layout = inflater.inflate(R.layout.custom_toast,
                    (ViewGroup) findViewById(R.id.custom_toast_container));
	//使用View对象的方法获取子对象(TextView类型)
    TextView text = (TextView) layout.findViewById(R.id.text);
    //动态设置TextView的文本
    text.setText("This is a custom toast");

    Toast toast = new Toast(getApplicationContext());//其实就是this
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);//设置位置
    toast.setDuration(Toast.LENGTH_LONG);//设置长短
    toast.setView(layout);//关键:使用上面创建和配置的View对象
    toast.show();//最终显示出来
    

kotlin:

    val inflater = layoutInflater
    val container: ViewGroup = findViewById(R.id.custom_toast_container)
    val layout: ViewGroup = inflater.inflate(R.layout.custom_toast, container)
    val text: TextView = layout.findViewById(R.id.text)
    text.text = "This is a custom toast"
    with (Toast(applicationContext)) {
        setGravity(Gravity.CENTER_VERTICAL, 0, 0)
        duration = Toast.LENGTH_LONG
        view = layout
        show()
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值