1、Toast控制項:
通過查看原始碼,發現Toast裡面實現的原理是通過服務Context.LAYOUT_INFLATER_SERVICE擷取一個LayoutInflater布局管理器,從而擷取一個View對象(TextView),設定內容將其顯示
複製代碼 代碼如下:
public static Toast makeText(Context context, CharSequence text, 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;
}
定義布局檔案:
複製代碼 代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="@+id/iv_my_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/notification" />
<TextView
android:id="@+id/tv_my_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="text"
/>
</LinearLayout>
自訂MyToast類:
複製代碼 代碼如下:
public class MyToast {
/**
* 顯示自訂的土司
* @param context 上下文
* @param iconid 表徵圖的id
* @param text 顯示的文本
*/
public static void showToast(Context context,int iconid, String text){
View view = View.inflate(context, R.layout.my_toast, null);
TextView tv = (TextView) view.findViewById(R.id.tv_my_toast);
ImageView iv = (ImageView) view.findViewById(R.id.iv_my_toast);
iv.setImageResource(iconid);
tv.setText(text);
Toast toast = new Toast(context);
toast.setDuration(0);
toast.setView(view);
toast.show();
}
}