Android说findViewById为null,而它存在于另一个活动的xml文件中
单击按钮后,将打开一个新的活动。我正在尝试从ActivityMain.kt向新活动添加视图。我知道如果我使用designer添加视图,这将很容易,但我不知道要添加多少视图。因此,我必须通过编程来完成这项工作 这是我的活动编号代码,这是我单击按钮时打开的另一个活动Android说findViewById为null,而它存在于另一个活动的xml文件中,android,android-studio,android-layout,kotlin,Android,Android Studio,Android Layout,Kotlin,单击按钮后,将打开一个新的活动。我正在尝试从ActivityMain.kt向新活动添加视图。我知道如果我使用designer添加视图,这将很容易,但我不知道要添加多少视图。因此,我必须通过编程来完成这项工作 这是我的活动编号代码,这是我单击按钮时打开的另一个活动 <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout
<?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>
以下是我得到的错误:
我也尝试过将代码输出到onClickListener,但没有成功。我也尝试过使用
import kotlinx.android.synthetic.main.activity\u number.*
startActivity
将启动一个新的活动
,但您的findViewById
正在“旧”活动中执行。您所遇到的错误是由您对不可为null的ConstraintLayout的强制转换引起的NullPointerException
如果要更新新的活动值,需要在新活动的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编码了O是的,我发现了错误。必须将导致错误的以下代码添加到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)
findViewById在活动的onCreate()方法的setContentView中指定的布局文件中工作。MainActivity中使用的布局是什么?如果需要在下一个活动中显示记录,并且值是字符串,为什么不在下一个活动中使用recyclerview?这样,您就可以在下一页将所有字符串的数组传递给recyclerview适配器,它将负责生成记录并显示它们。我试过了。这样做,应用程序就不会运行。@Pelocho说你的onClick
代码应该只启动NumbersActivity
,就这样。然后,NumbersActivity
可以像往常一样膨胀activity\u numbers.xml
布局文件,该布局就是您正在搜索的ID视图所在的位置MainActivity
无法准确查看它,我添加了一些代码供参考。请注意,您的新活动中没有单词列表
,因此您需要将其传递给其他人