android 自定义Toast显示风格
1.创建一个自己想要显示Toast风格的XML如下代码(toast_xml.xml):
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal"
- android:padding="8dp"
- android:background="#DAAA"
- android:id="@+id/toast_layout_root">
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginRight="8dp"
- android:id="@+id/iv"
- />
- <TextView android:id="@+id/text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textColor="#FFF"
- />
- </LinearLayout>
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显示就完成了;当然万变不离其宗,都是类似的做法。