Android自定义Toast的时长、位置、及显示的View
程序员文章站
2024-03-05 11:19:06
...
自定义时长
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();
}
上一篇: Android 两个Service的相互监视实现代码
下一篇: java并发之原子操作类和非阻塞算法
推荐阅读
-
Android自定义Toast的时长、位置、及显示的View
-
Android TextView显示Html类解析的网页和图片及自定义标签用法示例
-
Android TextView显示Html类解析的网页和图片及自定义标签用法示例
-
Android中自定义View实现圆环等待及相关的音量调节效果
-
Android中自定义View实现圆环等待及相关的音量调节效果
-
Android 自定义View 自定义动态进度圆环 动态数字显示 超级简单的方式
-
Android编程自定义对话框(Dialog)位置及大小的方法
-
Android自定义View设定到FrameLayout布局中实现多组件显示的方法 分享
-
Android编程自定义对话框(Dialog)位置及大小的方法
-
Android自定义View绘制的方法及过程(二)