วันนี้เราจะมาลองสร้าง Listener onclick ของ Button ใน android กัน โดยจะมีตัวอย่างการใช้งานอยู่ 4 แบบ โดยเราจะสร้างตัวอย่างง่ายๆโดยสร้าง Button ขึนมา 3 อันแล้วแต่ละอันก็จะกำหนดการทำงานคนละวิธีกัน ลองดูหน้าตาผลลัพธ์ก่อนแล้วกันนะครับ
การทำงานก็ง่ายๆ คือเมื่อกดแต่ละปุ่มก็จะแสดงข้อความว่า "This is message from button?" หน้าตาโปรแกรมดูธรรมดานะครับเราลองดูโค้ดกัน ก่อนอื่นคือ layout
การทำงานก็ง่ายๆ คือเมื่อกดแต่ละปุ่มก็จะแสดงข้อความว่า "This is message from button?" หน้าตาโปรแกรมดูธรรมดานะครับเราลองดูโค้ดกัน ก่อนอื่นคือ layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Listener Test" />
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="button1OnClickListener"
android:text="Button1"
/>
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2"
/>
<Button
android:id="@+id/btn3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button3"
/>
</LinearLayout>
ต่อไปเป็นโค้ดโปรแกรมทั้งหมดนะครับ