一,首先是自定义Toast,包括布局文件toast_view.xml、背景toast_view_bg.xml、以及自定义类MyToast.java,具体如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="@+id/toast_msg"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:gravity="center"
android:textColor="@color/colorWhite"
android:textSize="16dp"
android:background="@drawable/toast_view_bg"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!--自定义toast背景-->
<!-- 设置圆角 -->
<corners
android:radius="10dp"/>
<!-- 填充 -->
<solid
android:color="@color/translucentBlack"/>
</shape>
import android.app.Activity;
import android.content.Context;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import cn.cheng.dierrenge.livewallpaper.R;
/**
* Created by dierrenge on 2022/2/17.
* 自定义toast
*/
public class MyToast {
private MyToast() {}
public static Toast getInstance(Activity activity, String message) {
View toastView = activity.getLayoutInflater().inflate(R.layout.toast_view, null);
TextView textView = toastView.findViewById(R.id.toast_msg);
textView.setText(message);
Toast toast = new Toast(activity);
toast.setView(toastView);
toast.setDuration(Toast.LENGTH_SHORT);
return toast;
}
public static Message getMessage(String msg) {
Message message = new Message();
message.obj = msg;
return message;
}
}
二、在MainActivity的线程中使用,具体如下:
public class MainActivity extends AppCompatActivity {
// ......
// 多线程中使用toast
private Handler toastHandler = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 异步toast
toastHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
MyToast.getInstance(MainActivity.this,(String) msg.obj).show();
}
};
// 线程中使用
new Thread(() -> {
toastHandler.sendMessage(MyToast.getMessage("toast试一试"));
}).start();
}
}
以上全部,笔者水平有限,如有问题,还望指正。
|