要自定义 Android 11 中的 Toast,你可以按照以下步骤进行操作:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class CustomToast {
public static void showToast(Context context, String message) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_custom, null);
ImageView icon = view.findViewById(R.id.toast_icon);
TextView text = view.findViewById(R.id.toast_text);
// 设置自定义的图标和消息文本
icon.setImageResource(R.drawable.ic_info);
text.setText(message);
Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(view);
toast.show();
}
}
CustomToast.showToast(MainActivity.this, "This is a custom Toast");
这样就可以使用自定义布局和持续时间显示 Android 11 中的自定义 Toast 了。你可以根据需求修改 toast_custom.xml 中的布局和 CustomToast 类中的代码,以满足你的具体需求。