Android-重新包裝Toast,自定義背景
2016-4-27
Android L
算是包裝了一個自己使用的小工具。
使用Toast的目的是彈一個提示框。先看一下
Toast.makeText
方法。
Toast.makeText(getApplicationContext(), this, "彈出一個Toast", Toast.LENGTH_SHORT).show();
使用了Android自己的一個layout,然後把傳入的text放到layout的TextView中。
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
Toast result = new Toast(context);
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
我們想自定義個Toast背景,并且調用方法和原來的Toast類似。
觀察一下上面的Toast,使用的是Android裡面的View。在這一步把View改成我們自己的即可達到目的。
建立檔案
ToastCustom.java
public class ToastCustom {
public static final int LENGTH_SHORT = Toast.LENGTH_SHORT;
public static final int LENGTH_LONG = Toast.LENGTH_LONG;
Toast toast;
Context mContext;
TextView toastTextField;
public ToastCustom(Context context, Activity activity) {
mContext = context;
toast = new Toast(mContext);
toast.setGravity(Gravity.BOTTOM, 0, 260);// 位置會比原來的Toast偏上一些
View toastRoot = activity.getLayoutInflater().inflate(R.layout.toast_view, null);
toastTextField = (TextView) toastRoot.findViewById(R.id.toast_text);
toast.setView(toastRoot);
}
public void setDuration(int d) {
toast.setDuration(d);
}
public void setText(String t) {
toastTextField.setText(t);
}
public static ToastCustom makeText(Context context, Activity activity, String text, int duration) {
ToastCustom toastCustom = new ToastCustom(context, activity);
toastCustom.setText(text);
toastCustom.setDuration(duration);
return toastCustom;
}
public void show() {
toast.show();
}
}
建立一個layout
toast_view.xml
,裡面的style自己定義
<?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:id="@+id/toast_text"
style="@style/TextToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:background="@drawable/shape_toast"
android:textColor="@color/white" />
</LinearLayout>
調用方式和Toast一樣:
ToastCustom.makeText(getApplicationContext(), this, "彈出自定義背景Toast",
ToastCustom.LENGTH_SHORT).show();
之後就可以很友善地使用這個自定義背景的Toast