简体   繁体   中英

I am getting error when trying to setOnClickListener

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)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM