2017-02-17 43 views
1

我在選項卡式活動中使用多個片段來顯示json數據。
我想在每個片段收到響應時顯示進度條。Retrofit 2 - 如何在接收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!"); 
 
    } 
 
    });

+0

試圖顯示一個進度條,通過XML聲明它,但不能 –

+0

@LucaNicoletti我想顯示進度欄不進展對話?可能嗎? –

+0

你已經接受了答案。如果你想要另一個解決方案,請發佈另一個 –

回答

7

像這樣的東西,用progressDialog:在佈局

<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" /> 

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!"); 
     } 
    }); 
+0

賓果!解決了我的問題...我可以只顯示一個圓形進度條而不是對話嗎? –

+0

我想顯示進度條不是對話。可能嗎? –

0

簡單的一招 進度初始化進度

loadProgress = (ProgressBar) findViewById(R.id.progressBar); 

最後使之離開之後JSON負載競爭

loadProgress.setVisibility(View.Gone); 

然後讓它在一些用戶交互可見,然後終於走了完成JSON數據的加載時。簡單的假伎倆