SwipeRecyclerView 是基于 RecyclerView 的封装,提供了 Item 侧滑菜单、Item 滑动删除、Item 长按拖拽、添加HeaderView/FooterView、加载更多、Item点击监听等基本功能。
使用
1. 添加依赖
- 如果你使用的是android support库,那么请添加下述依赖:
implementation 'com.yanzhenjie.recyclerview:support:1.3.2'
- 如果你使用的是android x库,那么请添加下述依赖:
implementation 'com.yanzhenjie.recyclerview:x:1.3.2'
2. 在布局的 xml 中加入 SwipeRecyclerView
<com.yanzhenjie.recyclerview.SwipeRecyclerView
android:id="@+id/recyclerView"
android:overScrollMode="never"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3. 分割线
支持 Grid 形式和 Linear 形式,可以选择某个 ViewType 不画分割线:
// 默认构造,传入颜色即可。
ItemDecoration itemDecoration = new DefaultDecoration(color);
// 或者:颜色,宽,高,最后一个参数是不画分割线的ViewType,可以传入多个。
itemDecoration = new DefaultDecoration(color, width, height, excludeViewType);
// 或者:例如下面的123都是不画分割线的ViewType:
itemDecoration = new DefaultDecoration(color, width, height, 1, 2, 3);
recyclerView.setDecoration(itemDecoration);
4. 逻辑代码
public class LayoutActivity extends AppCompatActivity {
@BindView(R.id.recyclerView)
SwipeRecyclerView mRecyclerView;
private HomeAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
ButterKnife.bind(this);
initAdapter();
}
private void initAdapter() {
mAdapter = new HomeAdapter(R.layout.item_home,getHomeItem());
mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
Toast.makeText(LayoutActivity.this,"click"+position,Toast.LENGTH_SHORT).show();
}
});
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setSwipeMenuCreator(new SwipeMenuCreator() {
@Override
public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {
SwipeMenuItem deleteItem = new SwipeMenuItem(LayoutActivity.this);
deleteItem.setBackgroundColor(Color.parseColor("#FF3D39"))
.setText("删除")
.setTextColor(Color.WHITE)
.setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
.setWidth(170);
rightMenu.addMenuItem(deleteItem);
}
});
//菜单点击监听
mRecyclerView.setOnItemMenuClickListener(new OnItemMenuClickListener() {
@Override
public void onItemClick(SwipeMenuBridge menuBridge, int adapterPosition) {
menuBridge.closeMenu();
mAdapter.getData().remove(adapterPosition);
mAdapter.notifyDataSetChanged();
}
});
mRecyclerView.setAdapter(mAdapter);
}
private List<HomeBean> getHomeItem() {
List<HomeBean> list = Arrays.asList(
new HomeBean("android", R.mipmap.ic_launcher),
new HomeBean("ios", R.mipmap.ic_launcher),
new HomeBean("java", R.mipmap.ic_launcher),
new HomeBean("javascript", R.mipmap.ic_launcher),
new HomeBean("php", R.mipmap.ic_launcher),
new HomeBean("gyq", R.mipmap.ic_launcher),
new HomeBean("ysh", R.mipmap.ic_launcher)
);
List<HomeBean> infos = new ArrayList<>(list);
return infos;
}
}