1 layout_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="340dp"
android:layout_height="100dp"
android:gravity="center_vertical"
android:padding="13dp"
android:orientation="vertical" >
<TextView
android:id="@+id/toast_text"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textColor="#FFDDDDDD"
android:background="#0ADDDDDD"
android:gravity="center"
android:text="自定义"
android:textSize="26sp" />
</LinearLayout>
2.MyToastUtil.java
package com.geely.util;
import android.content.Context;
import android.support.annotation.StringRes;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.geely.main.R;
public class MyToastUtil {
private Toast mToast;
TextView textView;
int mDuration;
public @interface Duration {}
private MyToastUtil(Context context, @StringRes int resId, int duration) {
View v = LayoutInflater.from(context).inflate(R.layout.layout_toast, null);
textView = (TextView) v.findViewById(R.id.toast_text);
textView.setText(resId);
mToast = new Toast(context);
mToast.setDuration(duration);
mToast.setView(v);
}
public static MyToastUtil makeText(Context context, @StringRes int resId, int duration) {
return new MyToastUtil(context, resId, duration);
}
public void show() {
if (mToast != null) {
mToast.show();
}
}
public void setGravity(int gravity, int xOffset, int yOffset) {
if (mToast != null) {
mToast.setGravity(gravity, xOffset, yOffset);
}
}
public void setText(@StringRes int resId) {
textView.setText(resId);
}
public void setDuration(@Duration int duration) {
mDuration = duration;
}
}
3.使用
private MyToastUtil mytoast = null;
if (mytoast != null) {
mytoast.setText(R.string.noUpdate);
mytoast.show();
} else {
mytoast = mytoast.makeText(InfoActivity.this,R.string.noUpdate, Toast.LENGTH_SHORT);
mytoast.show();
}
网友评论