温馨提示×

如何改变toast.maketext的位置

小樊
82
2024-06-28 18:16:27
栏目: 编程语言

要改变Toast.makeText的位置,您可以通过创建一个自定义Toast布局来实现。以下是如何实现这一点的步骤:

  1. 创建一个自定义的Toast布局文件,命名为custom_toast.xml,其中包含您想要显示的内容,例如一个TextView。
<?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:layout_margin="16dp"
    android:background="#FF4081"
    android:padding="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Custom Toast"
        android:textColor="#FFFFFF"
        android:textSize="16sp" />

</LinearLayout>
  1. 在您的Activity中,使用LayoutInflater加载自定义的Toast布局文件,并通过setView方法将其设置为Toast的View。
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
    findViewById(R.id.custom_toast_container));

Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
  1. 如果您想要更改Toast的位置,可以使用setGravity方法来指定Toast显示的位置。
toast.setGravity(Gravity.TOP|Gravity.START, 0, 0);

通过这些步骤,您可以自定义Toast的布局并改变其显示的位置。

0