安卓 toast

来源:互联网 发布:手机刷机数据恢复 编辑:程序博客网 时间:2024/06/01 07:11

概述

一个 toast 是在屏幕上弹出一条信息,它的大小总是包裹着需要显示的内容,并且当前的 Activity 依然是可见并且可互动的。toast会自动消失,并且不接受任何互动事件。因为 toast 可以在后台的 Service 中创建,所以即使这个应用程序没有显示在屏幕上,仍然可以弹出 toast.

toast 最好用来显示简要的信息,比如断定用户正在注意屏幕时,弹出"File saved". toast 不能接受任何用户互动事件,如果需要用户响应并采取操作,考虑使用 状态栏通知 来替代.。

基本使用

首先,用makeText()方法实例化一个Toast对象。该方法需要三个参数:当前应用的Context,文本消息,和toast的持续时间。该方法返回一个实例化过的Toast对象。你可以用show()方法将该toast通知显示出来:
Toast.makeText(ToastActivity.this, "默认提示", Toast.LENGTH_SHORT).show();

指定显示位置

默认的,我们的toast提示是显示在底部正中间。我们还可以自己指定位置。通过setGravity
toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);

追加图片

默认toast只显示一个文本框,我们还可以追加图片或其他view进去
LinearLayout linearLayout = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(ToastActivity.this);
imageView.setImageResource(R.mipmap.ic_launcher);
linearLayout.addView(imageView);
首先,我们通过getView获得该toast的布局。之后,我们向布局中添加我们的布局,这里,我们添加一个简单的视图。

自定义布局

通常情况下,默认的布局很难满足我们的需求,在toast中也可以使用自定义布局。
View view1 = LayoutInflater.from(ToastActivity.this).inflate(R.layout.layout_toast, null);
toast.setView(view1);
使用inflate从xml文件中加载我们定义的布局,然后应用到toast上,xml布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
 
<ImageView
android:src="@drawable/qq_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_gravity="center_horizontal" />
 
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show_text"
android:id="@+id/textView"
android:layout_gravity="center_horizontal" />
</LinearLayout>

在线程中使用

根据安卓编程规范,我们不能再会UI线程中更改UI界面。toast是一个ui,因此,我们只有使用runOnUiThread来显示我们的信息
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast toast = Toast.makeText(ToastActivity.this, "线程中提示", Toast.LENGTH_SHORT);
toast.show();
}
});


















0 0