1. 程式人生 > >自定義Toast就是這麼簡單

自定義Toast就是這麼簡單

你是否很討厭安卓系統自帶的Toast風格?是的話那就來自定義吧,只需三步輕輕鬆鬆搞定。

        先來看看效果圖:

                                      

        第一步:  定義背景toast_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="@color/bg_gray" />

    <stroke
        android:width="1dp"
        android:color="@color/stroke_gray" />

    <corners android:radius="5dp" />

</shape>

       第二步:定義佈局custom_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/toast_bg" >

    <TextView
        android:id="@+id/toast_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:maxLines="2"
        android:padding="@dimen/text_margin"
        android:textColor="@color/text_black"
        android:textSize="@dimen/hint_textsize" />

</LinearLayout>

       第三步:自定義Toast類CustomToast

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.free.ui.R;

public class CustomToast {

	private static Toast toast=null;

	public static void showShortToast(Context context, String message) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		// 獲取自定義佈局例項	
		View view = inflater.inflate(R.layout.custom_toast, null);
		// 設定提示內容
		TextView text = (TextView) view.findViewById(R.id.toast_message);
		text.setText(message);
		// 確保只有一個Toast例項建立
		if (toast == null) {
			toast = new Toast(context);
			toast.setDuration(Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);		
		}
		// 載入自定義佈局
		toast.setView(view);
		toast.show();
	}
}

在需要使用Toast地方,呼叫CustomToast.showShortToast()方法就行了,很簡單吧?