Ad

Why Doesnt The OnClickListener Do Anything?

- 1 answer

Following a tutorial, I did set up onClick-Listeners before.

Now I am trying to make a simple app for listening to one stream, but my onClickListener doesn't do anything.

I created a new very simple app in android studio 3.3.2 to find out what is happening. I guess it is something very basic.

package com.example.musicplay;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);

        final Button play_button = findViewById(R.id.play_button);
        Log.i("Button found","this one: " + play_button.getText());

        play_button.setOnClickListener(new View.OnClickListener() {

            // The code in this method will be executed when the play button is clicked on.
            @Override
            public void onClick(View view) {

                Toast.makeText(MainActivity.this, "A click happened!", Toast.LENGTH_SHORT).show();

            }
        });

        setContentView(R.layout.activity_main);
    }
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/play_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/play_button"/>

</LinearLayout>

The toast message should appear when the button is clicked, but nothing happens.

Ad

Answer

You are calling setContentView twice. This will replace the view hierarchy set up by the first call. Remove the second call to setContentView.

Ad
source: stackoverflow.com
Ad