User_art User_art - 5 months ago 24
Android Question

Switch statement doesn't work in Android studio with Button

I'm beginner in Android and java programming, so i can't understand why my switch statement doesn't work with button elements.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
Button button1;
Button button2;
Button button3;
TextView textView;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
textView = (TextView) findViewById(R.id.textView);

View.OnClickListener onClickListener = new View.OnClickListener() {
@Override


here my problem

public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
textView.setText("Button1 was pressed");
break;
case R.id.button2:
textView.setText("Button2 was pressed");
break;
case R.id.button3:
textView.setText("Button3 was pressed");
break;
}
}
};



}
}


I'll be very gratefu if someone help me.

P.S.
I'm beginner in programming

Answer

You have not write setOnClickListner on Button and make sure your Activity implements View.OnClickListener see my code below.

button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);

Use this code.

public class MainActivity extends AppCompactActivity implements View.OnClickListener {

    Button button1;
    Button button2;
    Button button3;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        textView = (TextView)findViewById(R.id.textview) ;

        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.button1:
                textView.setText("Button1 was pressed");
                break;
            case R.id.button2:
                textView.setText("Button2 was pressed");
                break;
            case R.id.button3:
                textView.setText("Button3 was pressed");
                break;
        }

    }
}
Comments