Handler.post()解决非主线程更新UI

来源:互联网 发布:如何定制淘宝客app 编辑:程序博客网 时间:2024/06/05 20:12

在非主线程中调用了showMessage方法,结果报错:Can't create handler inside thread that has not called Looper.prepare()

private void showMessage(String msg) {        Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);        toast.setGravity(Gravity.CENTER, 0, 0);        toast.show();    }

原来Android中非主线程不能更新UI,Handler.post()方法可以解决这个问题:于是将showMessage方法稍作修改就可以了:

private void showMessage(String msg) {    mSg = msg;    mHandler.post(new Runnable() {            @Override            public void run() {              Toast toast = Toast.makeText(getApplicationContext(), mSg, Toast.LENGTH_SHORT);                  toast.setGravity(Gravity.CENTER, 0, 0);                  toast.show();            }        });


原创粉丝点击