Instantiating a View on non-UI thread

China☆狼群 提交于 2019-12-06 00:06:16

The definitive answer appears in the documentation for View, under the heading "Event Handling and Threading":

Note: The entire view tree is single threaded. You must always be on the UI thread when calling any method on any view. If you are doing work on other threads and want to update the state of a view from that thread, you should use a Handler.

So it's not just things that obviously affect the appearance of the UI, like addView(), but "any method on any View".

The discussion on android-developers that @CommonsWare linked to has more than one high-level engineer from the Android framework team confirming that this is to be taken seriously.

This is an example, in how to add a view to a FrameLayout using AsyncTask

public void addFLview(View view) {
    MyAsyncTask as = new MyAsyncTask();
    as.execute(view);
}

AsyncTask class

private class MyAsyncTask extends AsyncTask<View, Void, View> {
    @Override
    protected View doInBackground(View... params) {
        return params[0];
    }
    @Override
    protected void onPostExecute(View view) {
        super.onPostExecute(view);
        myFrameLayout.addView(view);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!