自訂Toast的顯示位置和顯示內容,自訂toast
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 <Button11 android:onClick="toast_1"12 android:layout_width="match_parent"13 android:layout_height="wrap_content"14 android:text="普通的toast" />15 <Button16 android:onClick="toast_2"17 android:layout_width="match_parent"18 android:layout_height="wrap_content"19 android:text="自訂的toast" />20 <Button21 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 @Override13 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 // 建立ImageView29 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 }