Android/Java จัดการอีเวนต์ด้วย android:onClick

ไฟล์ที่เกี่ยวข้อง

  • activity_main.xml
  • MainActivity.java

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClickA"
            android:text="Button A" />

        <Button
            android:id="@+id/buttonB1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClickB"
            android:text="Button B1" />

        <Button
            android:id="@+id/buttonB2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClickB"
            android:text="Button B2" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.phaisarn.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    public void onClickA(View view) {
        Toast.makeText(this, "Hello World!", Toast.LENGTH_SHORT).show();
    }

    public void onClickB(View view) {
        switch (view.getId()) {
            case R.id.buttonB1:
                Toast.makeText(this, "Hello B1", Toast.LENGTH_SHORT).show();
                break;
            case R.id.buttonB2:
                Toast.makeText(this, "Hello B2", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}