自定义Toast作为工具类进行使用,这里的效果是在顶端弹出Toast背景为红色
package com.example.sqgl.util;
import com.example.sqgl.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.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,root);
TextView text = (TextView) layout.findViewById(R.id.textView1);
text.setText(tvString);
toast = new Toast(context);
toast.setGravity(Gravity.TOP, 0, 100);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/toast_layout_root">
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="@color/red"
android:textColor="@color/white"
android:textSize="14sp"
android:text="自定义1" />
</LinearLayout>
在Activity中直接用就可以了
toastCommom.ToastShow(DaibanshijianActivity.this, (ViewGroup)findViewById(R.id.toast_layout_root), "您有"+content+"条待办事件");