温馨提示×

android Toast大全(五种情形)建立属于你自己的Toast

小云
104
2023-09-23 08:30:46
栏目: 编程语言

在Android开发中,Toast是一种简单的弹出提示,用于向用户显示临时的消息。下面是五种情形的Toast使用示例:

  1. 普通Toast:
Toast.makeText(getApplicationContext(), "普通Toast", Toast.LENGTH_SHORT).show();
  1. 带有图标的Toast:
Toast toast = Toast.makeText(getApplicationContext(), "带有图标的Toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastLayout = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.ic_icon);
toastLayout.addView(imageView, 0);
toast.show();
  1. 自定义布局的Toast:

首先,创建一个自定义的布局文件toast_custom.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:gravity="center"
android:orientation="horizontal"
android:padding="20dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_icon" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:text="自定义布局的Toast" />
</LinearLayout>

然后,在代码中使用自定义布局的Toast:

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_custom,
(ViewGroup) findViewById(R.id.toast_custom_layout));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
  1. 长时间显示的Toast:
Toast.makeText(getApplicationContext(), "长时间显示的Toast", Toast.LENGTH_LONG).show();
  1. 位置偏移的Toast:
Toast toast = Toast.makeText(getApplicationContext(), "位置偏移的Toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 100, 100);
toast.show();

除了以上的五种情形,你还可以根据自己的需求进行更多的扩展和定制,例如改变Toast的字体样式、背景颜色等。通过自定义Toast,你可以根据自己的喜好和应用的风格创建属于自己的Toast。

0