2 回答
TA贡献1811条经验 获得超4个赞
从 onCrete 中删除这一行并将其添加到 fetchDataFromServer() 方法中,如下所示。
public class FragmentA extends Fragment {
private AdapterEventStore mAdapter;
private List<Item> mStore;
private final String hostName = "https://xxx.xxx.xxx";
private View view;
private Context context;
private LottieAnimationView lottieAnimationView;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_a, container, false);
context = view.getContext();
lottieAnimationView = view.findViewById(R.id.ais_lav_loading);
lottieAnimationView.setVisibility(View.VISIBLE);
initRecyclerView();
return view;
}
private void initRecyclerView() {
RecyclerView store = view.findViewById(R.id.ais_rv_event_store);
store.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
mStore = new ArrayList<>();
mAdapter = new AdapterEventStore(context, mStore);
store.setAdapter(mAdapter);
fetchDataFromServer();
}
private void fetchDataFromServer() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
final Retrofit retrofit = new Retrofit.Builder()
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(hostName)
.build();
APIGetItem itemShop = retrofit.create(APIGetItem.class);
Call<ModelEventExclusive> call = itemShop.getEventStore(hostName);
call.enqueue(new Callback<ModelEventExclusive>() {
@Override
public void onResponse(Call<ModelEventExclusive> call, Response<ModelEventExclusive> response) {
Log.e("Response: ", response.body().getItems().get(0).getItemName());
mEventStore.addAll(response.body().getItems());
mAdapter.notifyDataSetChanged();
hideLottieAnimation();
}
@Override
public void onFailure(Call<ModelEventExclusive> call, Throwable t) {
hideLottieAnimation();
Toast.makeText(context, "Error:"+t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
Log.e("Error occurred: ", t.getMessage());
}
});
}
private void hideLottieAnimation(){
lottieAnimationView.cancelAnimation();
lottieAnimationView.setVisibility(View.GONE);
}
@Override
public void onResume() {
super.onResume();
lottieAnimationView.setVisibility(View.GONE);
}
}
添加回答
举报