toast的简单用法

废话不多说,直接上代码:

/**
 * toast自带的设置图片类型的方法
 *
 * @param view
 */
public void btn1(View view) {
    Toast toast = Toast.makeText(MainActivity.this, "带图片的toast", Toast.LENGTH_SHORT);
    ImageView imageView = new ImageView(this);
    imageView.setImageResource(R.mipmap.ic_launcher);

    toast.setGravity(Gravity.CENTER, 0, 0);//如果不加这个布局设置,图片就会显示在文字上面;
    LinearLayout toastView = (LinearLayout) toast.getView();//先获取toast的布局对象
    toastView.addView(imageView);//给布局对象添加view

    toast.show();
}

效果如下:

232801_krdm_2526599.png

设置toast的位置:

/**
 * 设置toast显示位置
 *
 * @param view
 */
public void btn2(View view) {
    Toast toast = Toast.makeText(getApplicationContext(), "lalala", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER, 0, 0);//在这里有各种选项,看单词就知道什么意思了
    toast.show();
}
//比较简单不贴图了


完全自定义的toast:

1. 布局文件  toast_define:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:background="@drawable/ab"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:background="#7030ff8f"
        android:drawableLeft="@android:drawable/btn_star_big_on"
        android:gravity="center"
        android:text="自定义toast布局"
        android:textSize="25sp" />

    <ImageView
        android:id="@+id/iv_content"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:background="#f9f9"
        android:src="@android:drawable/sym_def_app_icon" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:background="#7031ffff"
        android:gravity="center"
        android:text="完全自定义的toast"
        android:textSize="25sp" />

</LinearLayout>

2.代码部分:

/**
 * 完全自定义的toast布局
 *
 * @param view
 */
public void btn3(View view) {
    Toast toast = new Toast(this);
    View toastView = LayoutInflater.from(this).inflate(R.layout.toast_define, null);
    TextView content = (TextView) toastView.findViewById(R.id.tv_content);

    content.setText("烦烦烦烦");
    content.setTextColor(Color.parseColor("#ff0000"));

    toast.setGravity(Gravity.TOP, 0, 0);
    toast.setView(toastView);
    toast.show();
}

显示效果:

233754_Uh5N_2526599.png比较丑,讲究看看吧;



转载于:https://my.oschina.net/u/2526599/blog/644219

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值