[英]Implementing swipe to refresh on RecyclerView
我试图将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());
}
请帮我解决这个问题。
试试这个变化,希望能对您有所帮助
//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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.