我正在尝试向SwipeRefreshLayout
添加RecyclerView
。我怎么做?这是我的代码,但它不起作用:
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View consultantView = inflater.inflate(R.layout.fragment_consultant, container, false);
swipeContainer = (SwipeRefreshLayout) consultantView.findViewById(R.id.consultant_recyclerview);
retrieveConsultantList();
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeContainer.setRefreshing(false);
retrieveConsultantList();
practiceSpinner.setAdapter(consultantListAdapter);
consultantListAdapter.notifyDataSetChanged();
}
});
}
我的回收代码:
private void setUpConsultantRecyclerView(List<Consultant> consultantList) {
ConsultantRecylerViewAdapter consultantRecylerViewAdapter = new ConsultantRecylerViewAdapter(getContext(), consultantList);
consultantRecyclerView.setAdapter(consultantRecylerViewAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
consultantRecyclerView.setLayoutManager(linearLayoutManager);
consultantRecyclerView.setItemAnimator(new DefaultItemAnimator());
}
请帮我解决这个问题。
答案 0 :(得分:2)
尝试此更改,希望可以帮助您
//move adapter to global variable
ConsultantRecylerViewAdapter consultantRecylerViewAdapter ;
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View consultantView = inflater.inflate(R.layout.fragment_consultant, container, false);
swipeContainer = (SwipeRefreshLayout) consultantView.findViewById(R.id.consultant_recyclerview);
//move to here
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
consultantRecyclerView.setLayoutManager(linearLayoutManager);
//declare list first
consultantList = new ArrayList<>();
consultantRecylerViewAdapter = new ConsultantRecylerViewAdapter(getContext(), consultantList);
consultantRecyclerView.setAdapter(consultantRecylerViewAdapter);
retrieveConsultantList();
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeContainer.setRefreshing(false);
retrieveConsultantList();
practiceSpinner.setAdapter(consultantListAdapter);
consultantListAdapter.notifyDataSetChanged();
}
});
}
private void retrieveConsultantList(){
//put this code when finish load data from server
setUpConsultantRecyclerView(consultantListFromServer)
}
//this to refresh your RecyclerView
private void setUpConsultantRecyclerView(List<Consultant> consultantList) {
//clear old list
consultantList.clear();
//add new collection to list
consultantList.addAll(consultantList);
//refresh adapter
consultantRecyclerView.notifyDataSetChanged();
}