Android 7.0.2自定义Toast显示时间
时间: 2023-12-03 17:42:25 浏览: 129
你可以使用 `Handler` 和 `Toast` 的 `setDuration` 方法来自定义 `Toast` 的显示时间。以下是一个示例代码:
```java
final Toast toast = Toast.makeText(getApplicationContext(), "Custom Toast", Toast.LENGTH_LONG);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 2000); // 2秒后取消Toast
```
在这个示例中,`Toast` 的显示时间被设置为 `Toast.LENGTH_LONG`,但是我们使用 `Handler` 来在 2 秒后取消 `Toast` 的显示。你可以根据需要调整 `Handler` 中的延迟时间。
相关问题
Android 7.0.2自定义Toast显示时间 可以取消
在Android中,可以通过自定义Toast的布局文件和使用Handler来实现自定义Toast显示时间和取消。
首先,创建一个自定义的Toast布局文件,例如:
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#CC000000"
android:padding="10dp">
<ImageView
android:id="@+id/toast_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:src="@drawable/ic_info"/>
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"/>
</LinearLayout>
```
然后,在你的Activity中,使用以下代码创建自定义Toast:
```java
// 获取自定义布局文件
View toastView = LayoutInflater.from(this).inflate(R.layout.custom_toast_layout, null);
// 设置Toast显示的图片和文本
ImageView imageView = toastView.findViewById(R.id.toast_image);
imageView.setImageResource(R.drawable.ic_info);
TextView textView = toastView.findViewById(R.id.toast_text);
textView.setText("This is a custom Toast message.");
// 创建Toast对象
Toast toast = new Toast(this);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastView);
// 延迟显示Toast
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.show();
}
}, 2000);
// 取消Toast
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 5000);
```
上述代码中,首先获取自定义布局文件,并设置Toast显示的图片和文本。然后创建Toast对象,并使用Handler来延迟2秒显示Toast,并在5秒后取消Toast。通过调用Toast的cancel()方法可以取消正在显示的Toast。
Android 7.0.2自定义Toast显示时间 通过longclick触发,显示200秒
要实现自定义的Toast显示时间,可以通过以下步骤:
1. 创建一个自定义的Toast布局文件,例如toast_custom.xml,可以在其中添加任意的视图组件。
2. 在代码中获取该布局文件并创建Toast对象,例如:
```
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_custom, (ViewGroup) findViewById(R.id.toast_layout_root));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
```
3. 在长按事件的回调函数中设置Toast的显示时间为200秒,例如:
```
button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Toast toast = ... // 创建Toast对象
toast.setDuration(200000); // 设置显示时间为200秒
toast.show();
return true;
}
});
```
这样就可以实现自定义的Toast显示时间,通过长按触发显示,并且显示时间为200秒。
阅读全文