本文实例为大家分享了RecyclerView实现点击条目删除的具体代码,供大家参考,具体内容如下
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button mButton1;
private Button mButton2;
private Button mButton3;
private Button mButton4;
private Button mButton5;
private RecyclerView mRecyclerView;
private ArrayList mList;
private LinearLayoutManager mLinearLayoutManager;
private RvAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
mList = new ArrayList<>();
for (int i=0;i<20;i++){
mList.add(i+"item");
}
mAdapter = new RvAdapter(mList, this);
mRecyclerView.setAdapter(mAdapter);
//设置分割线
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
//设置默认布局
mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mAdapter.setOnItemClickListener(new RvAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
mAdapter.remove(position);
}
@Override
public void onItemLongClick(int position) {
mAdapter.remove(position);
}
});
}
private void findViews() {
mRecyclerView = findViewById(R.id.rv);
mButton1= findViewById(R.id.b1);
mButton2= findViewById(R.id.b2);
mButton3= findViewById(R.id.b3);
mButton4= findViewById(R.id.b4);
mButton5= findViewById(R.id.b5);
mButton1.setOnClickListener(this);
mButton2.setOnClickListener(this);
mButton3.setOnClickListener(this);
mButton4.setOnClickListener(this);
mButton5.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.b1:
mAdapter.addData(3);
mRecyclerView.scrollToPosition(0);
break;
case R.id.b2:
mAdapter.remove(mList.size()-1);
break;
case R.id.b3:
mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
break;
case R.id.b4:
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
//mRecyclerView.addItemDecoration(new android.support.v7.widget.DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL));
break;
case R.id.b5:
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
break;
}
}
}