如何 return 通过网络调用响应数据膨胀视图

How to return inflated view by web call response data

onCreateView 方法在未等待网络服务响应的情况下终止。自然地,视图返回 null。其他一切正常。我的意思在下面给出。

private View view;
private View notExistedOwnStory;
private View existedOwnStory;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

...

notExistedOwnStory = inflater.inflate(R.layout.tab_writestory, container, false);
existedOwnStory = inflater.inflate(R.layout.tab_deletestory, container, false);

checkOwnStory(storyID, username);

if(view == notExistedOwnStory){

       ...

    }

    if (view == existedOwnStory) {

        ...

    }

    return view;
}

private void checkOwnStory(final String storyID,final String username) {

    // Tag used to cancel the request
    String tag_string_req = "req_checkOwnStory";

    pDialog.setMessage("Checking Own Story ...");
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST, AppConfig.CHECK_OWN_STORY, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Checking Own Story Response: " + response.toString());
            hideDialog();

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (!error) {

                    // here is the set according to the response
                    view = existedOwnStory;

                } else {

                    view = notExistedOwnStory;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Checking Own Story Error: " + error.getMessage());
            Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to check own story url
            Map<String, String> params = new HashMap<String, String>();
            params.put("storyID", storyID);
            params.put("username", username);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

如果checkOwnStory方法完全结束,onCreateView方法相应工作怎么办?

这不是正确的设计。 onCreateView() 在主线程上运行,所以你不能简单地等待这个方法来膨胀视图。因此,您可以膨胀 XML(可能带有进度对话框)以显示临时进度。

在成功解析 JSON 后,您可以使用 Handler.post() 方法通过 public void onResponse(String response) 处理程序 post 消息。

您可以实施 handleMessage() 方法,并根据从 onResponse() 方法获得的消息,您可以通过编程方式 (addView) 或从 [=24= 添加您想要的任何视图] 文件可能是并将该视图更新为 View.VISIBLE.