【问题标题】:toast.getView() and toast.setView() is deprecated不推荐使用 toast.getView() 和 toast.setView()
【发布时间】:2020-09-26 09:43:30
【问题描述】:

我想向用户展示自定义吐司。但 toast.getView() 和 toast.setView() 在 android studio 中已被弃用。

这是我的代码:

Toast toast = Toast.makeText(context, "Show Toast", Toast.LENGTH_LONG);
View view = toast.getView();
view.setBackgroundResource(R.drawable.toast_background);
TextView text = view.findViewById(android.R.id.message);
text.setTextColor(Color.WHITE);
text.setPadding(15,0,15,0);
toast.show();



现在,如何在 android studio(java) 中自定义 toast?

【问题讨论】:

  • 根据文档,API >=30 不支持,建议改用 Snackbar。我想你也可以创建一个没有按钮的 Dialog,它会在特定时间后被关闭,这可能是最接近 Toast 的视觉效果
  • 我会做的。谢谢@Stachu。

标签: android android-studio toast android-toast


【解决方案1】:

创建新类

    public class WhiteCustomToast {
    public static void Make(Context context, String message) {
        Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            View view = toast.getView();
            view.setBackgroundResource(R.drawable.white_cutom_bg);
            TextView text = (TextView) view.findViewById(R.id.message);
            //text.setTextColor(context.getResources().getColor(R.color.white));
            text.setTextColor(Color.parseColor("#FFFFFFFF"));
            text.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            text.setTypeface(Utilities.Ubuntu_Regular);
            text.setTextSize(14f);
        }
        toast.show();
    }
}
        
        

并在主类或任何地方使用

WhiteCustomToast.Make(context, "Checking");

【讨论】:

    猜你喜欢
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2012-11-14
    • 1970-01-01
    • 2019-11-08
    • 2019-11-08
    • 2020-01-03
    相关资源
    最近更新 更多