0
点赞
收藏
分享

微信扫一扫

信息提醒之Toast-更新中

_LEON_ 2022-03-24 阅读 63


概述

Toast与对话框类似,也会在屏幕的某个位置弹出一个窗口,在窗口中可以显示文本、图片等信息

与对话框不同的是,Toast信息提示框不可获得焦点,而且在显示一定的时间后会自动关闭。

因此,再显示Toast信息提示框的同时,屏幕上的控件仍然可以继续操作。

Toast的基本用法

显示Toast需要使用​​android.widget.Toast​​类。

只显示文本的Toast

如果只是显示文本的话,可以用如下代码

Toast toast = Toast.makeText(this,"文字",Toast.LENGTH_LONG);
toast.show();

分析: 上述代码使用Toast类的静态方法创建了一个Toast对象。

该方法的第二个参数是要显示的信息,

第三个参数标识Toast提示信息显示的时间。

由于Toast没有按钮,也无法通过手机按键关闭Toast,所以只能通过显示时间的长短来控制Toast信息提示的时间自动关闭。

Toast.LENGTH_LONG , Toast.LENGTH_SHORT .

注意:在创建只显示文本的Toast对象时,建议使用Toast.makeText方法,而不要直接new Toast对象,虽然Toast类有setText方法,但是不能在使用new关键字创建Toast对象后设置Toast提示信息框的文本信息。一下代码会抛出异常

Toast toast = new Toast();
toast.setText("文字");// 此行代码会抛出异常
toast.show();

显示文本和图像的Toast- setView

信息提醒之Toast-更新中_xml

// 将布局文件转换为View
View view = getLayoutInflater().inflate(R.layout.activity_custom_toast, null);
// 设置提示文字
TextView tv = (TextView) view.findViewById(R.id.textview);
tv.setText("自定义Toast");
// Toast展示
Toast toast = new Toast(this);
toast.setView(view);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();

activity_custom_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:background="#9AC0CD"
android:orientation="horizontal" >

<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:src="@drawable/face" />

<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp" />

</LinearLayout>

如果同时多个Toast信息提示框,系统会将这些Toast信息提示框放到队列中,等前一个Toast信息提示框关闭后会显示下一个Toast信息提示框,也就是说Toast信息提示框是按顺序显示的

用PopupWindow模拟Toast提示信息框

背景是.9的图片

信息提醒之Toast-更新中_提示框_02

LayoutInflater inflater  = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.activity_popupwd_toast, null);

final PopupWindow popupWindow = new PopupWindow(view,500 ,200);
popupWindow.setTouchable(false);
popupWindow.showAtLocation(view, Gravity.CENTER_HORIZONTAL,20 ,0);


// 设置定时器,5秒后自动关闭
android.os.Handler handler = new android.os.Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
popupWindow.dismiss();
}
} , 5*1000);

activity_popupwd_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00FFFFFF"
android:orientation="vertical">

<TextView
android:id="@+id/tvMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/toast"
android:text="有个定时器 设置的5秒后关闭...."
android:textColor="#000"
android:textSize="18sp" />
</LinearLayout>



举报

相关推荐

0 条评论