Android 7.0.2自定义Toast显示时间 通过longclick触发,显示100秒
时间: 2023-11-29 13:05:24 浏览: 159
要实现自定义Toast显示时间,可以通过以下步骤进行:
1. 创建一个自定义的Toast布局文件,比如命名为custom_toast.xml。
2. 在自定义布局文件中添加一个TextView,并设置其显示内容。
3. 在Java代码中实例化该自定义布局文件,并设置其显示时间。
4. 在长按事件中触发该自定义Toast显示。
具体的代码实现如下:
1. 创建自定义Toast布局文件custom_toast.xml
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#88000000"
android:orientation="horizontal"
android:padding="20dp">
<TextView
android:id="@+id/custom_toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="18sp" />
</LinearLayout>
```
2. 在Java代码中实例化该自定义布局文件,并设置其显示时间。
```
// 实例化自定义布局文件
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, null);
// 设置Toast显示的文字内容
TextView text = (TextView) layout.findViewById(R.id.custom_toast_text);
text.setText("自定义Toast显示100秒");
// 设置Toast的显示时间为100秒
int toastDurationInMilliSeconds = 100000;
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
```
3. 在长按事件中触发该自定义Toast显示。
```
button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// 在长按事件中触发自定义Toast显示
// 实例化自定义布局文件
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, null);
// 设置Toast显示的文字内容
TextView text = (TextView) layout.findViewById(R.id.custom_toast_text);
text.setText("自定义Toast显示100秒");
// 设置Toast的显示时间为100秒
int toastDurationInMilliSeconds = 100000;
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
return true;
}
});
```
这样就可以在长按事件中触发一个自定义Toast,并设置其显示时间为100秒了。
阅读全文
相关推荐














