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="10dp"
android:background="#90000000"
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"
/>
</LinearLayout>
2.封装一个Toast共同类,当然也可以直接在activity运用,那么我是用共通类,当然只是简单的封装:
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.zjtd.bzcommunity.R;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by Administrator on 2017/2/17.
* Toast自定义工具类
*/
public class ToastCommom {
private static TextView text;
private static Toast toast;
/**
* 显示Toast
* @param context
* @param tvString
* @param cntime
*/
public static void ToastShow(Context context, String tvString, int cntime) {
if (toast == null) {
toast = new Toast(context);
toast.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
View layout = LayoutInflater.from(context).inflate(R.layout.toast_xml, null);
// ImageView mImageView = (ImageView) layout.findViewById(R.id.iv);
// mImageView.setBackgroundResource(R.drawable.ic_launcher);
text = (TextView) layout.findViewById(R.id.text);
toast.setView(layout);
showMyToast(toast, cntime);
}
text.setText(tvString);
text.setTextColor(0xFFFFFFFF);
text.setTextSize(16);
if(toast!=null){
toast.show();
}
}
//自定义停留时间
public static void showMyToast(final Toast toast, final int cnt) {
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
toast.show();
}
}, 0, 3000);
new Timer().schedule(new TimerTask() {
@Override
public void run() {
toast.cancel();
timer.cancel();
}
}, cnt);
}
}
3:调用方法
ToastCommom.ToastShow(this, "内容",3000);