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

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: [Android Studio Dev] การสร้างข้อความ Toast ตอนกด Button

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

โดย prakasit.bank » 09/06/2015 3:04 pm

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 1950 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 1950 times
Screenshot_3.png
Screenshot_3.png (22.92 KiB) Viewed 1950 times
เสร็จสิ้นการสร้างข้อความ Toast ตอนกด Button

ข้างบน