Retrofit 2 - 如何在接收JSON响应时显示进度条

Ome*_*ish 5 android retrofit2

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

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!");
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

小智 17

有了这样的东西,使用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!");
        }
    });
Run Code Online (Sandbox Code Playgroud)


Sum*_*ani 6

布局中的简单技巧进度条

  <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="?attr/actionBarSize"
        android:layout_weight="1" />
Run Code Online (Sandbox Code Playgroud)

初始化进度条

 loadProgress = findViewById(R.id.progressBar);
Run Code Online (Sandbox Code Playgroud)

最后在 json 加载竞争后让它消失

 loadProgress.setVisibility(View.GONE);
Run Code Online (Sandbox Code Playgroud)

然后让它在一些用户交互中可见,然后在 json 数据加载完成时最终消失。简单的假戏法