XML 中配置:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:orientation="vertical">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/refresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
接下来是代码的实现:
private void initData(View view) {
mDatas = new ArrayList<>();
for (int i = 0; i < 10; i++) {
mDatas.add(i+"");
}
final Myadapter mAdapter=new Myadapter();
refreshLayout = view.findViewById(R.id.refresh);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
refreshLayout.setRefreshing(false);
mDatas.add("15");
mAdapter.notifyDataSetChanged();
}
},2000);
}
});
recycleView = (RecyclerView) view.findViewById(R.id.recycleView);
recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
recycleView.setAdapter(mAdapter);
recycleView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.HORIZONTAL));
}
class Myadapter extends RecyclerView.Adapter<HomeFragment.MyViewHolder>{
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder holder = new MyViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.layout_item, parent, false));
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv.setText(mDatas.get(position));
}
@Override
public int getItemCount() {
return mDatas.size();
}
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv;
public MyViewHolder(View itemView) {
super(itemView);
tv = (TextView) itemView.findViewById(R.id.tv);
}
}