我们时常会用到Toast,但是源生的Toast有时会满足不了我们的需求,这就需要我们自定义了。
首先,来一个Toast工具类:
public class MyToast {
private Toast mToast;
private TextView textView;
public void showToast(Context context, String text){
View toastView = LayoutInflater.from(context).inflate(R.layout.mytoast, null);
if (mToast == null){
mToast = new Toast(context);
mToast.setView(toastView);
textView = (TextView) toastView.findViewById(R.id.toastText);
textView.setText(text);
}else {
textView.setText(text);
}
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.show();
}
//取消Toast(用于退出当前界面的时候)
public void cancelToast() {
if (mToast != null) {
mToast.cancel();
}
}
}
贴上xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:alpha="0.9"
android:id="@+id/toastText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/shapetoast"
android:text="1245"
android:gravity="center"
android:textColor="#000"
/>
</LinearLayout>
然后就是MainActiviy:
public class MainActivity extends AppCompatActivity {
private MyToast myToast;
private Context context;
//用来记录第几次点击,并且验证不会弹出多个Toast
private int count = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
myToast = new MyToast();
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
count++;
myToast.showToast(context, "第" + count + "次弹出自定的Toast");
}
});
}
//返回键退出
@Override
public void onBackPressed() {
myToast.cancelToast();
super.onBackPressed();
}
}
Demo下载