實現的Toast工具類ToastUtil封裝了普通文本消息提示和帶圖片的消息提示,實際開發中可根據自己的需要完善ToastUtil類,比如完善Toast消息位置相關設置等。
ToastUtil類代碼如下:
- package com.zyg.demo.toast;
-
- import Android.content.Context;
- import android.view.Gravity;
- import android.view.View;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.Toast;
-
- public class ToastUtil {
- private static Toast toast = null;
- public static int LENGTH_LONG = Toast.LENGTH_LONG;
- private static int LENGTH_SHORT = Toast.LENGTH_SHORT;
-
- /**
- * 普通文本消息提示
- * @param context
- * @param text
- * @param duration
- */
- public static void TextToast(Context context,CharSequence text,int duration){
- //創建一個Toast提示消息
- toast = Toast.makeText(context, text, duration);
- //設置Toast提示消息在屏幕上的位置
- toast.setGravity(Gravity.CENTER, 0, 0);
- //顯示消息
- toast.show();
- }
-
- /**
- * 帶圖片消息提示
- * @param context
- * @param ImageResourceId
- * @param text
- * @param duration
- */
- public static void ImageToast(Context context,int ImageResourceId,CharSequence text,int duration){
- //創建一個Toast提示消息
- toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
- //設置Toast提示消息在屏幕上的位置
- toast.setGravity(Gravity.CENTER, 0, 0);
- //獲取Toast提示消息裡原有的View
- View toastView = toast.getView();
- //創建一個ImageView
- ImageView img = new ImageView(context);
- img.setImageResource(ImageResourceId);
- //創建一個LineLayout容器
- LinearLayout ll = new LinearLayout(context);
- //向LinearLayout中添加ImageView和Toast原有的View
- ll.addView(img);
- ll.addView(toastView);
- //將LineLayout容器設置為toast的View
- toast.setView(ll);
- //顯示消息
- toast.show();
- }
- }
ToastUtil工具類應用示例代碼如下:
view plaincopy to clipboardprint?
- package com.zyg.demo.toast;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.Toast;
-
- import com.zyg.demo.toast.util.ToastUtil;
-
- public class ToastActivity extends Activity implements OnClickListener{
- private Button btnTxtToast = null;
- private Button btnImgToast = null;
- private Toast toast = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- initUI();
- }
-
- private void initUI(){
- btnTxtToast = (Button)findViewById(R.id.txttoast);
- btnTxtToast.setOnClickListener(this);
-
- btnImgToast = (Button)findViewById(R.id.imgtoast);
- btnImgToast.setOnClickListener(this);
- }
-
- @Override
- public void onClick(View v) {
- if(v==btnTxtToast){
- String text = "文本消息提示";
- int duration = ToastUtil.LENGTH_LONG;
- ToastUtil.TextToast(this, text, ToastUtil.LENGTH_LONG);
- }else if(v==btnImgToast){
- String text = "正在搜索";
- int ImageResourceId = R.drawable.search;
- int duration = ToastUtil.LENGTH_LONG;
- ToastUtil.ImageToast(this, ImageResourceId, text, duration);
- }
- }
- }
運行效果如下: