【问题标题】:Toast gives ClassCastExceptionToast 给出 ClassCastException
【发布时间】:2018-10-01 09:33:34
【问题描述】:

在某些设备中,例如 Samsung Galaxy Grand Duos android 7.1.2 我的自定义 Toast 给出了这个例外

java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.LinearLayout
          at ir.mrchabok.chabokpassenger.Helpers.Helper.MyToast(Helper.java:196)
          at ir.mrchabok.chabokpassenger.Activity.MapsActivity$4.onClick(MapsActivity.java:345)
          at android.view.View.performClick(View.java:5637)
          at android.view.View$PerformClick.run(View.java:22433)
          at android.os.Handler.handleCallback(Handler.java:751)
          at android.os.Handler.dispatchMessage(Handler.java:95)
          at android.os.Looper.loop(Looper.java:153)
          at android.app.ActivityThread.main(ActivityThread.java:6244)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)

我的自定义 Toast 代码是:

public static void MyToast(Context context, String text){
    Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
    LinearLayout toastLayout = (LinearLayout) toast.getView();
    TextView tvToast = (TextView) toastLayout.getChildAt(0);
    tvToast.setTypeface(globTypeFace);
    toast.show();
}

如您所知,toast 布局是 LinearLayout,我没有更改布局。

【问题讨论】:

  • 显然三星对Toasts 使用了不同的实现。事实上,您的解决方案有点老套,并且依赖于假设 - 我建议您采用另一种方法,例如使用 SpannableString 设置字体类型(请参阅this 答案),或者,如果自定义很重要,则使用自定义使用Toast#setView查看您的祝酒词
  • @PPartisan tank ,这似乎是正确的
  • @Radesh 在我的应用程序兄弟中工作正常

标签: android toast classcastexception


【解决方案1】:

java.lang.ClassCastException: android.widget.RelativeLayout 无法转换为 android.widget.LinearLayout

看起来视图是一种RelativeLayout而不是LinearLayout。所以你可以尝试将LinearLayout改为RelativeLayout。

顺便说一句,你最好使用 Toast#setView

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-07
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多