Issue
Getting error when I use button setOnClickListener
, also getting same error when use ViewBinding
.
My Mainactivity.java is looks like this
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
is showing error when I call to set in on button, and thats why I am also cant use setOnClickListener
to button.
my activity_main.xml is looks like this
<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" />
This is the error,
void android.view.View.setOnClickListener(android.view.View$OnClickListener)
Solution
The view you are setting as activity's view doesn't match with the one that contains the button you are trying to interact with.
Just replace:
setContentView(R.layout.activity_select_player);
With:
setContentView(R.layout.activity_main);
Answered By - AlexTa
Answer Checked By - David Marino (JavaFixing Volunteer)