Android開發(fā)系列(二十三):實現(xiàn)帶圖片提示的Toast提示信息框
來源:程序員人生 發(fā)布時間:2014-11-17 08:34:24 閱讀次數(shù):2549次
Android中的Toast是很常見的1個消息提示框,但是默許的消息提示框就是1行純文本,所以我們可以為它設(shè)置1些其他的諸如是帶上圖片的消息提示。
實現(xiàn)這個很簡單:
就是定義1個Layout視圖,然后設(shè)置Toast顯示自定義的View。
在這里,就是設(shè)置了1個LinearLayout容器,然后給這個容器添加圖片,添加文字信息。然后把這個容器設(shè)置給Toast對象,讓其顯示出來。
首先創(chuàng)建1個Android項目,然后我們編輯下main.xml文件:
<span style="font-size:14px;"><?xml version="1.0" encoding="utf⑻"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
>
<Button
android:id="@+id/simple"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="顯示簡單提示"
/>
<Button
android:id="@+id/bn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="顯示帶圖片的提示"
/>
</LinearLayout>
</span>
這里定義了兩個按鈕,1個是默許的Toast消息提示,另外1個是顯示帶圖片的信息提示。
接下來,我們就能夠編輯主界面的java代碼了:ToastTest.java
<span style="font-size:14px;">import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
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 ToastTest extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button simple = (Button) findViewById(R.id.simple);
// 為按鈕的單擊事件綁定事件監(jiān)聽器
simple.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
// 創(chuàng)建1個Toast提示信息
Toast toast = Toast.makeText(ToastTest.this
, "簡單的提示信息"
// 設(shè)置該Toast提示信息的延續(xù)時間
, Toast.LENGTH_SHORT);
toast.show();
}
});
Button bn = (Button) findViewById(R.id.bn);
// 為按鈕的單擊事件綁定事件監(jiān)聽器
bn.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View source)
{
// 創(chuàng)建1個Toast提示信息
Toast toast = new Toast(ToastTest.this);
// 設(shè)置Toast的顯示位置
toast.setGravity(Gravity.CENTER, 0, 0);
// 創(chuàng)建1個ImageView
ImageView image = new ImageView(ToastTest.this);
image.setImageResource(R.drawable.tools);
// 創(chuàng)建1個LinearLayout容器
LinearLayout ll = new LinearLayout(ToastTest.this);
// 向LinearLayout中添加圖片、原本的View
ll.addView(image);
// 創(chuàng)建1個ImageView
TextView textView = new TextView(ToastTest.this);
textView.setText("帶圖片的提示信");
// 設(shè)置文本框內(nèi)字體的大小和色彩
textView.setTextSize(30);
textView.setTextColor(Color.MAGENTA);
ll.addView(textView);
// 設(shè)置Toast顯示自定義View
toast.setView(ll);
// 設(shè)置Toast的顯示時間
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
}
});
}
}</span>
我們可以得到下邊的效果圖:

生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進行捐贈