我们要自定义一个Toast的话肯定要考虑到两点
- 要保证Toast运行在主线程中
- 我这写代码是放在Application类中的,放在activity也行,如果需要放到一个类中,那么handler的使用要注意使用
handlerThread
private static HandlerThread ht;
static {
ht = new HandlerThread("download thread");
ht.start();
}
private Handler mHandler = new Handler(ht.getLooper()) {...}
废话不多说、上代码
private Toast toast = null;
Handler displayMessageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.obj != null) {
displayToastMessage((String) msg.obj);
}
super.handleMessage(msg);
}
};
public void displayToastMessage(String message) {
if (message == null || "".equals(message))
return;
if (!isMainThread()) {
Message msg = new Message();
msg.obj = message;
displayMessageHandler.sendMessage(msg);
return;
}
if (toast != null)
toast.cancel();
LayoutInflater li = LayoutInflater.from(this);
View layout = li.inflate(R.layout.toastview, null);
toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
TextView text = (TextView) toast.getView().findViewById(R.id.toastText);
text.setTextColor(Color.BLACK);
text.setText(message);
toast.show();
}
public boolean isMainThread() {
return this.getMainLooper().getThread().equals(Thread.currentThread());
}
布局文件代码: toastview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toastRootLayout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<LinearLayout
android:id="@+id/toastLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="10dp"
android:background="#FF909090">
<TextView android:id="@+id/toastText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFFFFF"
android:gravity="center" />
</LinearLayout>
</LinearLayout>
网友评论