1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 android:orientation="vertical" 8 tools:context="com.example.leeson7_1_id19.MainActivity"> 9 10 <Button 11 android:onClick="toast_1" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:text="普通的toast" /> 15 <Button 16 android:onClick="toast_2" 17 android:layout_width="match_parent" 18 android:layout_height="wrap_content" 19 android:text="自定義的toast" /> 20 <Button 21 android:onClick="toast_3" 22 android:layout_width="match_parent" 23 android:layout_height="wrap_content" 24 android:text="自定義位置的toast" /> 25 </LinearLayout>
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical"> 6 7 <TextView 8 android:layout_width="match_parent" 9 android:layout_height="wrap_content" 10 android:text="自定義位置文本" 11 android:gravity="center" 12 android:background="#ff0000" 13 android:padding="5dp" 14 android:textSize="18sp"/> 15 16 17 </LinearLayout>
1 package com.example.leeson7_1_id19; 2 3 import android.os.Bundle; 4 import android.support.v7.app.AppCompatActivity; 5 import android.view.Gravity; 6 import android.view.View; 7 import android.widget.ImageView; 8 import android.widget.Toast; 9 10 public class MainActivity extends AppCompatActivity { 11 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16 } 17 18 public void toast_1(View V){ 19 // 設置土司顯示的內容和時長並顯示出來 20 Toast.makeText(this,"我是一個普通的toast",Toast.LENGTH_SHORT).show(); 21 } 22 public void toast_2(View V){ 23 // 自定義土司 24 // 創建土司 25 Toast toast = new Toast(this); 26 // 設置土司顯示的時間長短 27 toast.setDuration(Toast.LENGTH_SHORT); 28 // 創建ImageView 29 ImageView img = new ImageView(this); 30 // 設置圖片的資源路徑 31 img.setImageResource(R.mipmap.ic_launcher); 32 // 設置土司的視圖圖片 33 toast.setView(img); 34 // 顯示土司 35 toast.show(); 36 } 37 public void toast_3(View V){ 38 // 自定義土司顯示位置 39 // 創建土司 40 Toast toast = new Toast(this); 41 // 找到toast布局的位置 42 View layout = View.inflate(this,R.layout.toast,null); 43 // 設置toast文本,把設置好的布局傳進來 44 toast.setView(layout); 45 // 設置土司顯示在屏幕的位置 46 toast.setGravity(Gravity.FILL_HORIZONTAL|Gravity.TOP,0,70); 47 // 顯示土司 48 toast.show(); 49 } 50 }