Android 自定义Toast实现

来源:互联网 发布:淘宝高跟鞋 编辑:程序博客网 时间:2024/04/19 07:51

在Android开发过程中Toast是必不可少的一个组件。下面我们来说下如何自定义该组件使我们的应用更加美观

1、首先创建一个xml文件toast_text_widget.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@drawable/base_tip_bg" >    <TextView        android:id="@+id/toasttext"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_gravity="bottom"        android:layout_margin="@dimen/base_view_size_8"        android:background="#00000000"        android:gravity="center" /></LinearLayout> 

注:不能直接复制有些资源文件没有,这里只是给大家看下如何给你的Toast加上View


2、代码实现

如果你是在Activity直接写的话是:

View toastView = getLayoutInflater().inflate(R.layout.toast_text_widget, null);TextView toastText = (Textview)toastView.findViewById(R.id.toasttext);toastText.setText("你要显示的提示文字");Toast toastStart = new Toast(this);          toastStart.setGravity(Gravity.BOTTOM, 0, 10);          toastStart.setDuration(Toast.LENGTH_LONG);          toastStart.setView(toastView);          toastStart.show();

使用这种方法的话,每次用你都要写一下。所以最好定义成静态方法放在工具类中

/** * @param paramContext * @param paramString  提示文字 * @param showTime     Toast.LENGTH_LONG,显示时间长短 */public static void showToast(Context paramContext, String paramString, int showTime) {View toastView = LayoutInflater.from(paramContext).inflate(R.layout.toast_text_widget, null);TextView toasttext = (TextView) toastView.findViewById(R.id.toasttext);toasttext.setText(paramString);Toast toast = new Toast(paramContext);toast.setGravity(Gravity.BOTTOM, 0, 10);if (showTime == 1) {toast.setDuration(Toast.LENGTH_LONG);} else {toast.setDuration(Toast.LENGTH_SHORT);}toast.setView(toastView);toast.show();}

太囧笑话网出品

原创粉丝点击