我有一个自定义的吐司,它在java活动中有效,但在kotlin中不起作用,在kotlin活动中,它引发以下错误:
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)
这是烤面包:
<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()
我在这里做什么错了?
答案 0 :(得分:3)
我认为是因为findViewById
返回了可为空的值,但您还是想将其强制转换为非null类型。在这里,我对您的代码做了一些修改:
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()
希望这会对您有所帮助。
答案 1 :(得分:1)
Toast.makeText(applicationContext,"this is toast message",Toast.LENGTH_SHORT).show()
val toast = Toast.makeText(applicationContext, "Hello Javatpoint", Toast.LENGTH_SHORT)
toast.show()
val myToast = Toast.makeText(applicationContext,"toast message with gravity",Toast.LENGTH_SHORT)
myToast.setGravity(Gravity.LEFT,200,200)
myToast.show()
答案 2 :(得分:0)
避免findViewById的简便方法
在build.gradle(app)文件中,添加以下行。
apply plugin: 'kotlin-android-extensions'
现在,您可以在.kt文件中编写以下代码。
val inflater = layoutInflater
var inflatedFrame = inflater.inflate(R.layout.demo, null)
inflatedFrame.text.text = "Already reported"
val toast = Toast(context)
toast.setGravity(Gravity.BOTTOM, 0, 145)
toast.duration = Toast.LENGTH_LONG
toast.view = inflatedFrame
toast.show()