Android学习笔记二十之Toast吐司、Notification通知、PopupWindow弹出窗
Toast吐司
Toast吐司是我们经常用到的一个控件,Toast是AndroidOS用来显示消息的一种机制,它与Dialog不同,Toast不会获取到焦点,通常显示一段时间之后就会自动消失,下面我们来介绍Toast的几种常用方式:
第一种,默认显示方式,也是最常用的方式:
Toast.makeText(MainActivity.this, "这是默认的显示方式", Toast.LENGTH_SHORT).show();
第二种,自定义设置位置的显示方式:
Toast toast = Toast.makeText(MainActivity.this, "这是自定义显示位置的效果", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER, 0, 0);
toast.show();
第三种,带图片显示:
Toast toast = Toast.makeText(MainActivity.this, "这是带图片的效果", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER, 0, 0);
LinearLayout linearLayout = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(R.mipmap.ic_launcher);
linearLayout.addView(imageView, 0);
toast.show();
第四种,完全自定义显示方式:
LayoutInflater layoutInflater = getLayoutInflater();
View toastView = layoutInflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.ll_toast));
Toast toast = new Toast(MainActivity.this);
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(toastView);
toast.show();
布局文件代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_toast"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16sp"
android:layout_marginTop="16sp"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是完全自定义的吐司"
android:textSize="20sp" />
</LinearLayout>
第五种,其他线程通过handler显示:
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
}).start();
public void showToast() {
Toast.makeText