使用射击库消耗REST Web服务的活动不会显示从XML加载的布局(通过SetContentView())



我想拥有一项使用射击库消耗REST API的活动,同时在屏幕上显示自定义布局(用XML布局文件编写)。

所以我写了一项活动,该活动像往常一样在其ongreate()中调用 setContentView(R.layout.layout_file);之后,它通过射击库消耗了REST API(即构建射击的RequestQueue对象,然后在其上调用requestQueueObject.add(requestObject))。

(相关部分)代码如下。

问题是 是从REST API下载数据,使用setContentView()从XML布局文件加载的布局(在 onCreate() 消耗之前剩下的Web服务未显示在屏幕上,并且屏幕保持空白。然后在那之后,瞬间显示了XML中定义的布局,例如眨眼的眨眼,然后启动了下一个活动AnotherActivity

在下一个活动中,如果我按下后按钮,则在第一个活动中显示XML中的布局设置。

我如何解决此问题?

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
        RequestQueue requestQueue = RequestQueueSingleton.getInstance(getApplicationContext()).getRequestQueue();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        ...
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ...
                    }
                });
        requestQueue.add(request);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        startActivity(new Intent(this, AnotherActivity.class));
    } 

您应该了解更多有关Acitivty生命周期和线程的信息。

首先 - 直到onResume阶段才看到活动。因此,当您将线程在onCreate阶段内睡觉时,无法达到onResume(这就是为什么您会看到空白屏幕)。

第二 - 您不应依靠时间来找出请求何时完成。相反,在回调方法(Response.Listener<JSONObject>和/或Response.ErrorListener()

中启动所需的活动

ongreate您正在使线程入睡5秒,因此此问题。您可以通过进行以下更改来解决问题:

替换此代码:

try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        startActivity(new Intent(this, AnotherActivity.class));

new Handler().postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        startActivity(new Intent(this, AnotherActivity.class));
                    }
                }, 5000);

我猜您正在尝试实现飞溅屏幕 功能,此解决方案应为此起作用。

最新更新