WebView empty until I touch the component

2019-09-16 20:52发布

问题:

I'm doing a request with Volley Library. The response from the network is stored in a String. So, I load a webview with this data by the next way:

webView.loadData(response, "text/html; charset=UTF-8", null);

My problem is that the web is loaded, but It is only showed when I touch the webview. What I can do to update the view?

Source Code:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_register_oauth, container, false);

        //Queue of petitions
        volley_queue = Volley.newRequestQueue(container.getContext());

        webView = (WebView) view.findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);

        //MANDAR PETICION
        StringRequest postReq = new StringRequest(Request.Method.POST, pathto.get_register_service(), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("VolleyReq", "onResponse\n " + response);
                webView.loadData(response, "text/html; charset=UTF-8", null);
                webView.reload();
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("VolleyReq", "onResponse\n " + error);
            }

        });

        volley_queue.add(postReq);

        return view;
    }

Thank you.

回答1:

This code works to me:

getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadData(received_response, "text/html; charset=UTF-8", null);
                    }
                });