RecyclerView是Android中常用的列表控件,它可以用于展示大量数据,并支持灵活的布局和交互。在RecyclerView中实现水平布局并隐藏选定项目的方法如下:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" />
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
// 数据集合
private List<String> data;
// 构造方法
public MyAdapter(List<String> data) {
this.data = data;
}
// 创建ViewHolder
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
// 绑定ViewHolder
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String item = data.get(position);
holder.textView.setText(item);
}
// 获取数据数量
@Override
public int getItemCount() {
return data.size();
}
// ViewHolder定义
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
}
}
}
RecyclerView recyclerView = findViewById(R.id.recyclerView);
List<String> data = new ArrayList<>();
// 添加数据到data集合中
// ...
MyAdapter adapter = new MyAdapter(data);
recyclerView.setAdapter(adapter);
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String item = data.get(position);
holder.textView.setText(item);
// 判断是否为选定项目
if (position == selectedPosition) {
// 隐藏该项
holder.itemView.setVisibility(View.GONE);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
params.width = 0;
params.height = 0;
holder.itemView.setLayoutParams(params);
} else {
// 显示该项
holder.itemView.setVisibility(View.VISIBLE);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
params.width = RecyclerView.LayoutParams.WRAP_CONTENT;
params.height = RecyclerView.LayoutParams.WRAP_CONTENT;
holder.itemView.setLayoutParams(params);
}
}
以上就是在RecyclerView水平布局上隐藏选定项目的方法。通过设置选定项目的布局参数为隐藏,可以实现该项在布局中不可见的效果。
腾讯云相关产品推荐:
领取专属 10元无门槛券
手把手带您无忧上云