Retrofit 2 - 如何在接收 JSON 响应时显示进度条 [英] Retrofit 2 - How to show progress bar On Receiving JSON Response

查看:26
本文介绍了Retrofit 2 - 如何在接收 JSON 响应时显示进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在选项卡式活动中使用多个片段来显示 json 数据.
我想在每个片段中收到响应时显示进度条.

I am using multiple Fragments in tabbed activity to show json data.
I want to show progress bar whenever the response is received in every fragment.

private void loadJSON() {
  Retrofit retrofit = new Retrofit.Builder()
                                  .baseUrl(BASEURL)
                                  .addConverterFactory(GsonConverterFactory.create())
                                  .build();
  newsAPI = retrofit.create(NewsAPI.class);
  Call<JSONResponse> call = newsAPI.topNews("soure", "api-key");

  call.enqueue(new Callback<JSONResponse>() {
    @Override
    public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
      Log.v("this", "Yes!");
    }

    @Override public void onFailure(Call<JSONResponse> call, Throwable t) {
      Log.v("this", "No Response!");
    }
  });
}

推荐答案

使用progressDialog :

With something like this, using progressDialog :

private void loadJSON() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        newsAPI = retrofit.create(NewsAPI.class);
        Call < JSONResponse > call =
                newsAPI.topNews("soure", "api-key");

        // Set up progress before call
        final ProgressDialog progressDoalog;
        progressDoalog = new ProgressDialog(MainActivity.this);
        progressDoalog.setMax(100);
        progressDoalog.setMessage("Its loading....");
        progressDoalog.setTitle("ProgressDialog bar example");
        progressDoalog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // show it
        progressDoalog.show();

        call.enqueue(new Callback < JSONResponse > () {

            @Override
            public void onResponse(Call < JSONResponse > call, Response < JSONResponse > response) {
                // close it after response
                progressDoalog.dismiss();
                Log.v("this", "Yes!");
            }
        }

        @Override public void onFailure(Call < JSONResponse > call, Throwable t) {
            // close it after response
            progressDoalog.dismiss();
            Log.v("this", "No Response!");
        }
    });

这篇关于Retrofit 2 - 如何在接收 JSON 响应时显示进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆