最近的项目需要实现一个多标签展开收起的效果,具体效果如下
收起效果
展开效果 拿到效果图,很自然会想到用RecyclerView
来实现,但是至于具体怎么去收起和展开,我这里用了个取巧的办法,可能不是最好的办法,但也能达到要求,在此,主要作为记录用,大神轻喷。 废话不多说,直接上代码才是最实在的。 外层布局代码: 复制代码
布局预览效果
这里点击展开和收起的按钮,我单独用了个TextView
来实现,因为这样操作起来最简单,少了很多逻辑处理。(没办法,有点懒……) 接下来是 RecyclerView
中 item 的布局实现,代码如下: 复制代码
布局都写完了之后,我们直接看 adapter
适配器的实现代码:
public class MyAdapter extends RecyclerView.Adapter{ private Context context; private List list; public MyAdapter(Context context) { this.context = context; } @Override public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false); return new MyHolder(v); } @Override public void onBindViewHolder(MyHolder holder, final int position) { String name = list.get(position).getName() ; holder.tv.setText(name); } @Override public int getItemCount() { return list == null ? 0 : list.size(); } //隐藏 public void setHideList(List newList) { this.list = newList; notifyDataSetChanged(); } //展开 public void setOpenList(List openList) { this.list = openList; notifyDataSetChanged(); } //不需要隐藏/展开 public void setRealList(List realList) { this.list = realList; notifyDataSetChanged(); } //清除数据 public void clearData() { if (list != null) { this.list.clear(); notifyDataSetChanged(); } } class MyHolder extends RecyclerView.ViewHolder { TextView tv; public MyHolder(View itemView) { super(itemView); tv = itemView.findViewById(R.id.tvName); } }}复制代码
TextView 绑定展开收起事件
/** * 处理展开收缩的逻辑 */ tvOpenTips.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isOpen) { adapter.setHideList(hideList); tvOpenTips.setText("展开全部"); tvOpenTips.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.detail_open, 0); isOpen = false; } else { adapter.setOpenList(openList); tvOpenTips.setText("收起全部"); tvOpenTips.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.detail_close, 0); isOpen = true; } } });复制代码
设置展开收起的数据源
private void setData() { if (list.size() > 4) { //设置大于多少条数据开始隐藏 for (int i = 0, j = list.size(); i < j; i++) { openList.add(list.get(i)); } for (int i = 0; i < 4; i++) { hideList.add(list.get(i)); } adapter.setHideList(hideList); } else { adapter.setRealList(list); } tvOpenTips.setVisibility(list.size() > 4 ? View.VISIBLE : View.GONE); rv.setAdapter(adapter); }复制代码