android - Android 说 findViewById 为空,而它存在于另一个活动的 xml 文件中
问题描述
单击按钮后,将打开一个新活动。我正在尝试将视图添加到来自 ActivityMain.kt 的新活动。我知道如果我使用设计器添加视图会很容易,但我不知道要添加多少视图。因此,我必须以编程方式执行此操作。
这是我的 activity_numbers 代码,这是我单击按钮时打开的另一个活动。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/activity_numbers_root_view"
tools:context=".NumbersActiviy">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/numbers_text"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
这是 MainActivity.kt 文件中的代码
numbersText.setOnClickListener {
val intent: Intent = Intent(this, NumbersActiviy::class.java)
startActivity(intent)
// Commenting the following code, the application works just fine.
val numbersRootView:ConstraintLayout = findViewById(R.id.activity_numbers_root_view)
val textView = TextView(numbersRootView.context)
textView.text = "This is from " + wordsList.get(0)
numbersRootView.addView(textView)
}
这是我得到的错误: 错误的图像
我也尝试将代码放在 onClickListener 之外,但没有奏效。我也尝试过使用
import kotlinx.android.synthetic.main.activity_numbers.*
解决方案
startActivity
将启动一个新Activity
的,但您findViewById
正在“旧”活动中执行。您遇到的错误是 NullPointerException
由您的强制转换为不可空值引起的ConstraintLayout
如果要更新新的 Activity 值,则需要在onCreate
新 Activity 的方法中添加代码。就像是
class MainActivity {
...
numbersText.setOnClickListener {
val intent: Intent = Intent(this, NumbersActiviy::class.java)
/* add extras to intent */
startActivity(intent)
}
...
}
class NumbersActivity {
fun onCreate(...) {
val numbersRootView:ConstraintLayout = findViewById(R.id.activity_numbers_root_view)
val textView = TextView(numbersRootView.context)
textView.text = "This is from " + /* get extra from intent? */
numbersRootView.addView(textView)
}
}
请注意,您需要在意图中传递额外内容。检查这个问题
我不记得确切的语法,自从我为 Android 编码以来已经有一段时间了