【发布时间】:2021-11-19 22:20:45
【问题描述】:
不知道为什么我在使用按钮 setOnClickListener 时会出错。
Mainactivity.java
package com.codeavenge.tictactoe;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.codeavenge.tictactoe.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_player);
button=(Button) findViewById(R.id.play);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Hello", Toast.LENGTH_SHORT).show();
}
});
}
}
我的代码中的这个错误在哪里?当我使用视图绑定而不是 findViewById 时,也会出现同样的问题。 activity_main.xml
<?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:background="@color/background_bg"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:text="@string/tic_tac_toe"
android:textColor="#5E5E5E"
android:textSize="50sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteY="195dp" />
<Button
android:id="@+id/play"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:background="@drawable/button_bg"
android:text="@string/play"
android:textColor="@color/white"
android:textSize="34sp"
app:cornerRadius="30dp"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.672" />
</androidx.constraintlayout.widget.ConstraintLayout>
原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' 在 com.codeavenge.tictactoe.MainActivity.onCreate(MainActivity.java:19)
【问题讨论】:
-
您展示了您的 activity_main 布局,但您正在加载一个名为 activity_select_player 的布局。
标签: java android android-studio