android 自定义Toast显示风格

1.创建一个自己想要显示Toast风格的XML如下代码(toast_xml.xml):



    


2.封装一个Toast共同类,当然也可以直接在activity运用,那么我是用共通类,当然只是简单的封装:

import com.sbr.activity.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("ResourceAsColor")
public class ToastCommom {
	
	private static ToastCommom toastCommom;
	
	private Toast toast;
	
	private ToastCommom(){
	}
	
	public static ToastCommom createToastConfig(){
		if (toastCommom==null) {
			toastCommom = new ToastCommom();
		}
		return toastCommom;
	}
	
	/**
	 * 显示Toast
	 * @param context
	 * @param root
	 * @param tvString
	 */
	
	public void ToastShow(Context context,ViewGroup root,String tvString){
		View layout = LayoutInflater.from(context).inflate(R.layout.toast_xml,root);
		TextView text = (TextView) layout.findViewById(R.id.text);
		ImageView mImageView = (ImageView) layout.findViewById(R.id.iv);
		mImageView.setBackgroundResource(R.drawable.ic_launcher);
		text.setText(tvString);
		text.setTextColor(R.color.aqua);
		toast = new Toast(context);
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(layout);
		toast.show();
	}

}

3.创建一个Activity去引用该共通类:

import com.sbr.commonView.ToastCommom;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class ToastActivity extends Activity {
	
	private Button mbutton;
	
	private ToastCommom toastCommom;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.toast_buton);
		toastCommom = ToastCommom.createToastConfig();
		mbutton = (Button) findViewById(R.id.btn);
		mbutton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				toastCommom.ToastShow(ToastActivity.this, (ViewGroup)findViewById(R.id.toast_layout_root), "你好");
			}
		});
		
	}
	
}


好了,一个简单的自定义toast显示就完成了;当然万变不离其宗,都是类似的做法。

你可能感兴趣的:(android学习,android,toast自定义,toast,android自定义toast,toast自定义组件)