Three buttons, three different actions/outputs

You almost had it, you just had some basic things wrong, I added comments to help you understand what is going on:

public class MainActivity extends Activity implements View.OnClickListener {
    //Declare views
    //You first have to declare your views (Button, TextView, EditText etc)
    Button text_edit, activity2, activity3;
    TextView text, activitytext2, activitytext3;

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

        //Initialize views
        //You don't have to create a method when initializing your views
        //but it keeps your code in order
        initViews();

        //Set onclick listeners
        //Declare your click listeners and pass it the context of you activity "this"
        text_edit.setOnClickListener(this);
        activity2.setOnClickListener(this);
        activity3.setOnClickListener(this);
    }

    private void initViews() {
        text_edit = findViewById(R.id.text_edit);
        text = findViewById(R.id.text_edit2);
        activity2 = findViewById(R.id.activity2);
        activitytext2 = findViewById(R.id.activitytext2);
        activity3 = findViewById(R.id.activity3);
        activitytext3 = findViewById(R.id.activitytext3);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.text_edit:
                //Set text to TextView
                text.setText("Kolla, kolla vad hon kan!");
                break;
            case R.id.activity2:
                //Start Activity2
                Intent intent1 = new Intent(this, Activity2.class);
                startActivity(intent1);
                break;
            case R.id.activity3:
                //Start Activity3
                Intent intent2 = new Intent(this, Activity3.class);
                startActivity(intent2);
                break;
        }
    }
 }

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top