Android自定义实现好看的toast

jopen 10年前

系统已经给我们提供了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即可

q1.png

q2.png