Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實現 Toast 提示框圖文並存的方法

編輯:關於 Android 程式設計

Toast 是 Android 中最常用的輕量提示手段。本文透過一個實例,說明如何讓 Toast 同時顯示圖片與文字,並自訂其顯示位置。

下面的程式碼在點擊按鈕後,會組裝一個包含 ImageView 與 TextView 的 LinearLayout,透過 setView() 設定為 Toast 的內容,並用 setGravity() 調整它在螢幕上的相對位置。

 import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.text.util.Linkify; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class A05Activity extends Activity { private Button b; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b=(Button)findViewById(R.id.button); b.setText("顯示Toast"); b.setBackgroundColor(Color.GREEN); b.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub ImageView iv=new ImageView(A05Activity.this); iv.setImageResource(R.drawable.icon); TextView tv=new TextView(A05Activity.this); tv.setText(R.string.title); LinearLayout ll=new LinearLayout(A05Activity.this); //判斷TextView中的內容是什麼格式,並與系統連接 Linkify.addLinks(tv, Linkify.PHONE_NUMBERS|Linkify.EMAIL_ADDRESSES|Linkify.WEB_URLS); Toast t=Toast.makeText(A05Activity.this, tv.getText(), Toast.LENGTH_LONG); View v1=t.getView(); ll.setOrientation(LinearLayout.VERTICAL); ll.addView(iv); ll.addView(v1); t.setView(ll); //設置Toast對象在手機中的相對位置 t.setGravity(Gravity.CENTER, 50, 50); t.show(); } }); } } 

這裡要特別注意:由於 Toast 屬於 Activity 中的 Context,其中的連結是無法點擊的。也就是說,即使 Toast 裡含有網址等內容,也無法在 Toast 上直接點擊開啟。掌握這一點,就能避免在使用時踩坑。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved