【Android代码片段之六】Toast工具类(实现带图片的Toast消息提示)
转载请注明出处,原文网址:http://blog.csdn.net/m_changgong/article/details/6841266 作者:张燕广
实现的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工具类应用示例代码如下:
- 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);
- }
- }
- }
运行效果如下:
路漫漫其修远兮 吾将上下而求索