以下的例子將呈現如何在Toast 秀出來的短訊中,加入小圖示
先來談一下一般的Toast 的用法,
Toast toast=Toast.makeText(context, text, duration);
toast.show();
而如果要設定Toast 的位置,則可以用
toast.setGravity(Gravity.TOP|Gravity.RIGHT, 0, 0);
來設定。
要在Toast 中加入圖示的方法為:
先設定一個layout: customtoast.xml,設定為LinearLayout ,id 為toast_layout_root。內含一個Image與TextView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#DAAA" android:orientation="horizontal">
<ImageView
android:id="@+id/mandsm"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFFF"
/>
</LinearLayout>
在Activity 中使用LayoutInflater;來解析XML檔,生成視圖元件,LayoutInflater 必須使用getLayoutInflater來取得正在運作的實體,
LayoutInflater inflater=getLayoutInflater();
利用Inflater.inflate 傳回一個View
也可以用
LayoutInflater inflater=LayoutInflater.from(ctxt);
或是
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
來獲得。
layout=inflater.inflate(R.layout.customtoast
,(ViewGroup) findViewById(R.id.toast_layout_root));
設定image 的圖檔與TextView 的文字。
ImageView image = (ImageView) layout.findViewById(R.id.mandsm);
image.setImageResource(R.drawable.ic_launcher);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Short custom message");
在OnClick 事件中,可以利用
Toast(getApplicationContext())取得 toast ,
toast.setView(layout);
toast.show()
來呈現。
程式下載
沒有留言:
張貼留言