我发现从API 30开始唯一可以显示自定义Toast的方法是即时创建它们。
XML布局
根据需要进行自定义
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".main_activity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp"
android:layout_margin="18dp"
android:background="@drawable/ad_hoc_toast_background"
android:textColor="#1e1e1e"
android:gravity="center"
android:visibility="gone"
android:layout_alignParentBottom="true"
android:id="@+id/ad_hoc_toast_textview"
tools:text="Temporary message bla bla bla ..."/>
</RelativeLayout>
烤面包提示背景(ad_hoc_toast_background.xml)
根据需要自定义
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="220dp"
android:height="100dp"/>
<corners
android:radius="25dp"
/>
<solid
android:color="#e6ffffff"
/>
</shape>
</item>
</selector>
定义 show_ad_hoc_toast() 方法
private void show_ad_hoc_toast(final TextView ad_hoc_toast_textview, String text){
ad_hoc_toast_textview.setText(text);
AlphaAnimation animation1 = new AlphaAnimation(0f, 1f);
animation1.setDuration(300);
animation1.setFillAfter(true);
animation1.setAnimationListener(new Animation.AnimationListener() {
@Override public void onAnimationStart(Animation animation){}
@Override public void onAnimationRepeat(Animation animation){}
@Override public void onAnimationEnd(Animation animation){
new CountDownTimer(2250, 1) {
public void onTick(long millisUntilFinished){}
public void onFinish() {hide_ad_hoc_toast(ad_hoc_toast_textview);}
}.start();
}
});
ad_hoc_toast_textview.setVisibility(View.VISIBLE);
ad_hoc_toast_textview.startAnimation(animation1);
}
定义 hide_ad_hoc_toast() 方法
private void hide_ad_hoc_toast(final TextView ad_hoc_toast_textview){
AlphaAnimation animation1 = new AlphaAnimation(1f, 0f);
animation1.setDuration(300);
animation1.setFillAfter(true);
animation1.setAnimationListener(new Animation.AnimationListener() {
@Override public void onAnimationStart(Animation animation) { }
@Override public void onAnimationRepeat(Animation animation) { }
@Override public void onAnimationEnd(Animation animation) {
ad_hoc_toast_textview.setVisibility(View.GONE);
}
});
ad_hoc_toast_textview.startAnimation(animation1);
}
需要时从您的代码中调用该方法
//Find ad_hoc_toast textview
TextView ad_hoc_toast_textview = findViewById(R.id.ad_hoc_toast_textview);
//Define the text to be shown
String text = "This is the custom toast message"
//Show the ad_hoc toast
show_ad_hoc_toast(ad_hoc_toast_textview, text);
结果
![结果](https://istack.dev59.com/B2SOk.gif)