[Android Studio Dev] การสร้างข้อความ Toast ตอนกด Button

Mobile Application Developing- Android, iOS, Window Phone สอนเขียนโปรแกรมบนมือถือ ระบบปฏิบัติการต่าง แอนดรอยด์ ไอโอเอส วินโดโฟน สอนเขียนโปรแกรมบนมือถือ

Moderator: mindphp, ผู้ดูแลกระดาน

prakasit.bank
PHP Super Member
PHP Super Member
โพสต์: 316
ลงทะเบียนเมื่อ: 02/06/2015 9:47 am

[Android Studio Dev] การสร้างข้อความ Toast ตอนกด Button

โพสต์ที่ยังไม่ได้อ่าน โดย prakasit.bank »

Toast คือการแสดงข้อความแจ้งเตือนผ่าน Popup ที่ลอยอยู่เหนือ Activity ปัจจุบัน โดยที่ Activity ปัจจุบันนั้นยังคงทำงานอยู่อย่างปกติ โดยจะแสดงให้เห็นถึงการเขียนคำสั่งภายใน Class Activity มาเริ่มสร้างข้อความ Toast กันเลย

วิธีสร้างโปรเจค

ขั้นตอนที่ 1 : สร้างปุ่มขึ้นมา 1 ปุ่ม

โค้ด: เลือกทั้งหมด

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toast"
        android:id="@+id/button01"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        />

</RelativeLayout>
Screenshot_1.png
Screenshot_1.png (47.31 KiB) Viewed 1949 times
ขั้นตอนที่ 2 : มาที่ MainActivity.java สร้าง Method onclick และเชื่อมต่อกับปุ่มใน xml

โค้ด: เลือกทั้งหมด

public void onClickToast(View view){
        Button btn_next = (Button)findViewById(R.id.button01);
    }
ขั้นตอนที่ 3 : สร้าง Toast ข้อความข้างใน Method

โค้ด: เลือกทั้งหมด

public void onClickToast(View view){
        Button btn_next = (Button)findViewById(R.id.button01);
        Toast.makeText(getApplicationContext(),"Test Toast",Toast.LENGTH_LONG).show();
    }
ตรง " " ให้เราใส่ข้อความที่จะให้แสดงเป็น pop up (ex. "Test Toast")
  • Toast.LENGTH_LONG = แสดงข้อความ Toast ยาว
  • Toast.LENGTH_SHORT = แสดงข้อความ Toast สั้น
ขั้นตอนที่ 4 : ใส่ onclick ของปุ่มใน xml

โค้ด: เลือกทั้งหมด

android:onClick="onClickToast"
จะได้ตามนี้

โค้ด: เลือกทั้งหมด

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toast"
        android:id="@+id/button01"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="onClickToast"
        />
ทดสอบ
Screenshot_2.png
Screenshot_2.png (21.62 KiB) Viewed 1949 times
Screenshot_3.png
Screenshot_3.png (22.92 KiB) Viewed 1949 times
เสร็จสิ้นการสร้างข้อความ Toast ตอนกด Button
รูปภาพ
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 74