Android 如何实现toast内容过长跑马灯的展示效果
时间: 2024-05-04 19:19:31 浏览: 13
Android 中可以通过自定义 Toast 布局,在 TextView 中设置 `android:ellipsize="marquee"` 和 `android:singleLine="true"` 属性来实现 Toast 内容过长时的跑马灯效果。
下面是一个示例:
1. 在 res/layout 目录下创建一个自定义的 Toast 布局文件,例如 `toast_layout.xml`,内容如下:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/toast_bg">
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:padding="10dp"
android:ellipsize="marquee"
android:singleLine="true"
android:focusable="true"
android:marqueeRepeatLimit="marquee_forever"
android:focusableInTouchMode="true" />
</LinearLayout>
```
2. 创建一个自定义的 Toast 类,例如 `CustomToast.java`,代码如下:
```java
public class CustomToast {
public static void showToast(Context context, String message, int duration) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_layout, null);
TextView textView = view.findViewById(R.id.toast_text);
textView.setText(message);
Toast toast = new Toast(context);
toast.setView(view);
toast.setDuration(duration);
toast.show();
}
}
```
3. 在需要显示 Toast 的地方调用 `CustomToast.showToast()` 方法即可,例如:
```java
CustomToast.showToast(MainActivity.this, "这是一条很长很长的 Toast 消息,测试跑马灯效果!", Toast.LENGTH_SHORT);
```
其中 `duration` 参数为 Toast 显示的时长,可以为 `Toast.LENGTH_SHORT` 或 `Toast.LENGTH_LONG`。
注意:在使用跑马灯效果时,需要将 TextView 的 `focusable` 和 `focusableInTouchMode` 属性设置为 true,否则跑马灯效果无法生效。