问题描述
我想创建一个自定义视图,该视图可以选择动态数量的复选框,例如 Uber Eats 优食或任何其他食品订购应用。你能分享一下想法吗?将其显示为 recyclerview 或 listview 是个好主意吗?
解决方法
请在您的要求中尝试以下实现方式
在活动或片段中
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"/>
LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
以下代码用于适配器类
onBindViewHolder{
Model model = list.get(position);
if (model.isSelected()) {
holder.imageViewSelect.setImageResource(R.mipmap.check);
} else {
holder.imageViewSelect.setImageResource(R.mipmap.uncheck);
}
}
linearCheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos = getAdapterPosition();
if(pos >= 0 && list != null && pos < list.size()){
for(int i=0;i<list.size();i++){
Model model = list.get(i);
model.setSelected(false);
list.set(i,model);
notifyItemChanged(i);
}
Model model = list.get(pos);
cancelReason.setSelected(true);
list.set(pos,model);
listener.selectValue(pos);
imageViewSelect.setBackgroundResource(R.mipmap.check);
notifyItemChanged(pos);
}
}
});
在适配器的 xml 中
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView_select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:src="@mipmap/uncheck" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:lineSpacingExtra="3sp"
android:padding="@dimen/margin_padding_15"
android:text="Banana"
android:textColor="@color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="3sp"
android:padding="@dimen/margin_padding_15"
android:text="$200"
android:textColor="@color/black" />
</LinearLayout>