自定义实现好看的toast

3 篇文章 0 订阅
1 篇文章 0 订阅

系统已经给我们提供了toast,但是有时候风格和我们应用的整体风格不搭配,这个时候,我们需要,自定义来实现toast,比较简单。

主要代码如下:

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:gravity="center"
    >
    <ImageView
        android:id="@+id/toast_img"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:src="@drawable/ic_launcher"
        />
     <TextView
          android:background="@drawable/toast_shap"
        android:id="@+id/toast_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:gravity="center"
        android:textColor="#ffffff"
        android:textSize="14sp"
        android:textStyle="bold" />

</LinearLayout>

这个xml定义了一个有图片的toast

xml2:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
     <TextView
          android:background="@drawable/toast_shap"
        android:id="@+id/toast_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:gravity="center"
        android:textColor="#ffffff"
        android:textSize="14sp"
        android:textStyle="bold" />

</LinearLayout>

纯文本的toast


java代码,很简单,把它封装在一个类里面,其他地方就可以随时使用了

public static void toast(Context context,String content)
    {
        view=LayoutInflater.from(context).inflate(R.layout.toast_item, null);      //加载布局文件
        TextView textView=(TextView) view.findViewById(R.id.toast_text);    // 得到textview
        textView.setText(content);     //设置文本类荣,就是你想给用户看的提示数据
        Toast toast=new Toast(context);     //创建一个toast
        toast.setDuration(Toast.LENGTH_SHORT);          //设置toast显示时间,整数值
        toast.setGravity(Gravity.CENTER, Gravity.CENTER, Gravity.CENTER);    //toast的显示位置,这里居中显示
        toast.setView(view);     //設置其显示的view,
        toast.show();             //显示toast
    }



代码很简单,你可以根据自己需求,为toast设置不同的view即可


完整例子下載地址:http://download.csdn.net/detail/hhhccckkk/5337410


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值