在activity_xml
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipeRefresh"
android:layout_width=“match_parent”
android:layout_height=“0dp”
android:layout_weight=“9”>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width=“match_parent”
android:layout_height=“match_parent”>
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
适配器里
public void setData(List<NewsBean.DataBeanX.DataBean> data,boolean isRefreshing) {
if (data != null && data.size() > 0) {
if (isRefreshing){
this.data.clear();//用之前clear
}
this.data.addAll(data);
notifyDataSetChanged();
}
}
//mainActivity
@Override
public void initView() {
recyclerView = findViewById(R.id.recyclerview);
progressBar = findViewById(R.id.progress);
swipeRefreshLayout = findViewById(R.id.swipeRefresh);
}
@Override
public void initData() {
mainPresenter = new MainPresenter();
mainPresenter.setView(this);
mainPresenter.getDataFromNet();
//上拉刷新
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
isRefreshing=true;
mainPresenter.getDataFromNet();
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(MainActivity.this,“刷新成功”,Toast.LENGTH_SHORT).show();
}
});
//下拉加载
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int visibleItemCount=linearLayoutManager.getChildCount();
int itemCount = linearLayoutManager.getItemCount();
int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
if (visibleItemCount+firstVisibleItemPosition>=itemCount){
if (progressBar.getVisibility()!=View.VISIBLE){
isRefreshing=false;
mainPresenter.getDataFromNet();
progressBar.setVisibility(View.VISIBLE);
}
}
Toast.makeText(MainActivity.this,“加载成功”,Toast.LENGTH_SHORT).show();
}
});
myAdapter = new MyAdapter(this);
myAdapter.setCallback(new MyAdapter.DeleteCallback() {
@Override
public void delete(int position) {
data.remove(position);
myAdapter.setData(data,isRefreshing);
myAdapter.notifyDataSetChanged();
}
});
recyclerView.setAdapter(myAdapter);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
}
@Override
public int setSelfContentView() {
return R.layout.activity_main;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onSuccess(NewsBean newsBean) {
data = newsBean.getData().getData();
progressBar.setVisibility(View.GONE);
myAdapter.setData(data,isRefreshing);
}
@Override
public void onError(int code, String message) {
}
}