我尝试使用一个按钮从一个主要活动切换到另一个活动,但是当我尝试运行该应用程序时,它在单击该应用程序后立即自行关闭。我在命令中发现错误消息:Unable to start activity ComponentInfo{fr.amseu.mystretching/fr.amseu.mystretching.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
我在 MainActivity 中的代码是这样的:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button = findViewById<ImageButton>(R.id.imageButton)
button.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent);}
这是我的主要活动:
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/item_main"
android:background="@color/light_red">
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="100dp"
android:layout_height="120dp"
app:cardCornerRadius="8dp"
app:cardElevation="5dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageButton
android:id="@+id/imageButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/lower_legs"
android:contentDescription="@string/home_page_first_button" />
</androidx.cardview.widget.CardView>
<View
android:id="@+id/view_separation"
android:layout_width="match_parent"
android:visibility="invisible"
android:layout_height="1dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="@+id/name_item"
style="@style/SubTitleTextStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/default_margin"
android:text="@string/home_page_first_button"
app:layout_constraintBottom_toTopOf="@+id/view_separation"
app:layout_constraintStart_toEndOf="@+id/cardView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/description_item"
style="@style/DefaultTextStyle"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="@string/home_page_description_1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="@+id/name_item"
app:layout_constraintTop_toBottomOf="@+id/view_separation" />
</androidx.constraintlayout.widget.ConstraintLayout>
对于我的回收器视图,我在页面中采用此模型,以下项目是同级项目,但我使用适配器 HomeFragment 更改图像和文本...
有人能帮助我吗 ?
(这是我的第一个应用程序)
多谢 !
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)