编码实现
**ToastUtils.java**
public class ToastUtils {
private static Toast mToast;
public static void showShortText(String text){
showText(text,Toast.LENGTH_SHORT);
}
public static void showLongText(String text){
showText(text,Toast.LENGTH_LONG);
}
public static void showText(String text,int duration){
if (TextUtils.isEmpty(text)){
return;
}
TextView tvText;
if (mToast == null){
mToast = Toast.makeText(MyApplication.getContext(), "", Toast.LENGTH_SHORT);
final View toastLayout = ((LayoutInflater) MyApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.toast_layout, null);
tvText = toastLayout.findViewById(R.id.toast_text);
mToast.setView(toastLayout);
}else {
mToast.cancel();
mToast = Toast.makeText(MyApplication.getContext(), "", Toast.LENGTH_SHORT);
final View toastLayout = ((LayoutInflater) MyApplication.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.toast_layout, null);
tvText = toastLayout.findViewById(R.id.toast_text);
mToast.setView(toastLayout);
}
mToast.setDuration(duration);
tvText.setText(text);
mToast.show();
}
// 普通方法.....
public static void showToast(String msg, int duration) {
mToast = Toast.makeText(MyApplication.getContext(), "", duration);
mToast.setText(msg);
mToast.show();
}
}
```
**toast_layout.xml**
```clike
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/toast_root"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_toast">
<TextView
android:textSize="13.5sp"
android:textColor="@color/white"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:id="@+id/toast_text"
android:layout_gravity="center_horizontal"
android:shadowColor="#BB000000"
android:shadowRadius="2.75"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
**bg_toast**
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="6dp"/>
<solid android:color="#cc555555" />
</shape>
使用
ToastUtils.showShortText("1111");
总结
自定义背景效果还是比较简单的,有利于统一机型效果,不是很复杂。主要是从toast源码提供的api我们进行了相应的扩展,容易的实现是建立在对原理的理解与运用上的,多多注重基础,一起前进。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:http://blog.itpub.net/69978258/viewspace-2704117/