gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:15:12 34 4
gpt4 key购买 nike

我有一个自定义 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com