java - Toast 适用于 Java Activity ,但不适用于 kotlin

标签 java android kotlin

我有一个自定义 toast,它在 java Activity 中有效,但在 kotlin 中无效,在 kotlin Activity 中,它抛出以下错误:

kotlin.TypeCastException: null cannot be cast to non-null type android.view.ViewGroup 

在这条线上

val layout = inflater.inflate(R.layout.custom_toast,
      findViewById<View>(R.id.custom_toast_container) as ViewGroup)

这是 toast :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="8dp"
android:background="@color/colorPrimary"
>
<ImageView android:src="@drawable/ic_done_black_24dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="8dp"
    android:tint="@color/colorBackground"
    />
<TextView android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#FFF"
    />

我如何在 java 中调用它:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_container));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Already reported");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 145);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

android studio如何将其转换为kotlin:

 val inflater = layoutInflater
 val layout = inflater.inflate(R.layout.custom_toast,
 findViewById<View>(R.id.custom_toast_container) as ViewGroup)

 val text = layout.findViewById<View>(R.id.text) as TextView
 text.text = "Already reported"
 val toast = Toast(context)
 toast.setGravity(Gravity.BOTTOM, 0, 145)
 toast.duration = Toast.LENGTH_LONG
 toast.view = layout
 toast.show()

我在这里做错了什么?

最佳答案

我认为这是因为 findViewById 返回可为空,但您正在尝试转换为非空类型。在这里我稍微修改了你的代码:

 val inflater = layoutInflater
 val layout = inflater.inflate(R.layout.custom_toast,
 findViewById<View>(R.id.custom_toast_container) as ViewGroup?)

 val text = layout?.findViewById<View>(R.id.text) as TextView?
 text?.text = "Already reported"
 val toast = Toast(context)
 toast.setGravity(Gravity.BOTTOM, 0, 145)
 toast.duration = Toast.LENGTH_LONG
 toast.view = layout
 toast.show()

希望对您有所帮助。

关于java - Toast 适用于 Java Activity ,但不适用于 kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858155/

相关文章:

android - Firebase 身份验证和数据库加密

android状态栏在浅色主题中透明

kotlin - 如何修改调用扩展函数的对象本身?

java - Spring :为什么在单元测试中加载应用程序上下文时需要添加javax.el-api依赖项?

java - 如何用Java编写惰性删除二叉搜索树的findMinimum

Java递归二分查找

android - 字符串到整数不起作用

android - MediaStore 从特定路径列出

java - 告诉 gradle 包含同一工作区中的 Eclipse 项目

android - Kotlin中的音乐URI空指针异常