[英]Android is saying that findViewById is null, whereas it is present in xml file of another activity
單擊該按鈕,將打開一個新活動。 我正在嘗試將 addView 添加到 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 值,您需要在新 Activity 的onCreate
方法中編寫代碼。 就像是
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 編碼以來已經有一段時間了
哦,是的,我發現了錯誤。 以下導致錯誤的代碼必須添加到newActivity.kt
文件中,而不是添加到mainActivity.kt
文件中。 這樣做之后,代碼就可以正常工作了。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.