2017-04-14 72 views
0

我是新來的改造,我有一個問題。我只想創建一個對服務器的調用,然後在我的應用程序的不同地方使用下載的數據。我使用的ViewPager只有很少的片段,每個片段都需要DataResponse類中的相同數據來創建不同的視圖。什麼是最好的方式來做到這一點,以及它會是什麼樣子?這是我的改裝課程的樣子。提前致謝!將一種類型的數據傳遞到不同的地方(改造)

public class ApiClientFactory { 

    public static final String baseURL = "https://earthquake.usgs.gov/fdsnws/event/1/"; 

    public ApiClient createApiClient(){ 
     Retrofit retrofit = new Retrofit.Builder() 
       .baseUrl(baseURL) 
       .addConverterFactory(GsonConverterFactory.create()) 
       .build(); 

     return retrofit.create(ApiClient.class); 
    } 
} 

public interface ApiClient { 

    @GET("query") 
    Call<DataResponse> getData(@QueryMap Map<String, String> options); 
} 

回答

0

我假設你有一個包含ViewPager的Activity。在activity的onCreate()方法中,您可以發出該請求。當您收到響應時,您可以構建適配器(FragmentPagerAdapter)並將您的DataResponse傳遞到那裏。在適配器中,您可以使用DataResponse構建片段並設置參數。

示例代碼:

public class YourActivity extends AppCompatActivity { 

    private FragmentPagerAdapter mAdapter; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ...// 

     makeRequest(); //Implement this method to get Data 
    } 

    //When the response is received call this method 
    private void onResponse(DataResponse response) { 
     //create your adapter 
     mAdapter = new CustomPagerAdapter(response, getSupportFragmentManager()); 

     //don't forget to set adapter to the ViewPager 
    } 

    static class CustomPagerAdapter extends FragmentPagerAdapter { 

     DataResponse mResponse; 

     CustomPagerAdapter(DataResponse response, FragmentManager fm) { 
      super(fm); 
      mResponse = response; 
     } 

     @Override 
     public Fragment getItem(int position) { 
      //create your fragments and set arguments 

      return CustomFragment.instance(mResponse); 
     } 

     @Override 
     public int getCount() { 
      return 1; //number of your fragments 
     } 
    } 
} 

public class CustomFragment extends Fragment { 
    private static final String KEY_RESPONSE = "key_response"; 

    public static CustomFragment instance(DataResponse response) { 
     Bundle args = new Bundle(); 
     args.putParcelable(KEY_RESPONSE, response); 
     CustomFragment f = new CustomFragment(); 
     f.setArguments(args); 
     return f; 
    } 

    @Override 
    public void onViewCreated(View root, Bundle savedInstanceState) { 
     super.onViewCreated(root, savedInstanceState); 
     DataResponse response = getArguments().getParcelable(KEY_RESPONSE); 

     //do with the response whatever you want 
    } 
} 

確保DataResponse實現Parcelable接口。

相關問題