Android自定义Toast的时长、位置、及显示的View

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010356768/article/details/82771310

自定义时长

Android自带的两个时长
Toast.LENGTH_LONG 默认显示3.5秒
Toast.LENGTH_SHORT 默认显示2秒

如何让Toast在3.5秒内自定义显示长度:

public static void showShort(Context context, String msg, int duration) {
        final Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        toast.show();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                toast.cancel();
            }
        }, duration);
    }

***注意duration为毫秒

自定义位置

关键代码

public void showToastTop(Context context, String msg) {
        Toast toast = Toast.makeText(context,msg,Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }
    public void showToastCenter(Context context, String msg) {
        Toast toast = Toast.makeText(context,msg,Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER|Gravity.RIGHT, 0, 0);
        toast.show();
    }
    public void showToastBottom(Context context, String msg) {
        Display display = getWindowManager().getDefaultDisplay();
        int height = display.getHeight();
        Toast toast = Toast.makeText(context,msg,Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM, 0, height / 6);
        toast.show();
    }

自定义View

添加一个自定义的布局toast.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/toast_shape"
    android:padding="10dp"
    android:minWidth="100dp">

    <TextView
        android:id="@+id/tv_toast"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="18dp"
        android:textColor="#FFFFFF"
        />
</LinearLayout>

其中toast_shape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="5dp"/>
    <solid android:color="#5c5c5c"/>
</shape>

关键代码

 public static void showToast(Context context, String msg) {
        Toast toast = new Toast(context);
        //设置Toast显示位置,居中,向 X、Y轴偏移量均为0
        toast.setGravity(Gravity.CENTER, 0, 0);
        //获取自定义视图
        View view = LayoutInflater.from(context).inflate(R.layout.toast, null);
        TextView tvMessage = (TextView) view.findViewById(R.id.tv_toast);
        //设置文本
        tvMessage.setText(msg);
        //设置视图
        toast.setView(view);
        //设置显示时长
        toast.setDuration(Toast.LENGTH_SHORT);
        //显示
        toast.show();
    }

猜你喜欢

转载自blog.csdn.net/u010356768/article/details/82771310