public class MyToast {
private Activity context;
public MyToast(Activity mcontext){
this.context=mcontext;
}
//在主线程和子线程中显示
public void showMyToast(final String messages) {
if ("main".equals(Thread.currentThread().getName())) {
showToast(messages);
} else {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
showToast(messages);
}
});
}
}
//toast初始化和布局
private void showToast(final String text){
Toast toast =new Toast(context);
LayoutInflater inflater =context.getLayoutInflater();
View toastLayout=inflater.inflate(R.layout.mytoast,(ViewGroup)context.findViewById(R.id.toast));
TextView textView=(TextView)toastLayout.findViewById(R.id.toastText);
textView.setText(text);
toast.setGravity(Gravity.BOTTOM,0,0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastLayout);
toast.show();
}
}
private Activity context;改成 private Context context;试试
用getApplicationContext()