vrund purohit vrund purohit - 6 months ago 93
Android Question

CardView click event and focus at same time

I have one

CardView
with custom selector which include focus state to true

<android.support.v7.widget.CardView
android:id="@+id/cvColor"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:layout_marginBottom="4dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp"
android:foreground="@drawable/card_color_size"
android:minHeight="50dp"
android:visibility="gone"
app:cardCornerRadius="3dp"
app:cardElevation="4dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true" >


My need is when I click on card it should be clicked as well as focused too. so I did something like this.

@Override
public void onBindViewHolder(final ViewHolderCard1 viewHolder,
final int position) {
viewHolder.size.setVisibility(View.VISIBLE);
viewHolder.tvSize.setText(size.get(position).get("size"));
viewHolder.size.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
posSize = position;
Toast.makeText(getApplicationContext(), "" + posSize,
Toast.LENGTH_SHORT).show();
viewHolder.size.setFocusableInTouchMode(true);
}
});
}


now when I click once of the item of
RecycleView
it works fine, both
Toast
and focus happens same time.

But as soon as I click next item it just like on first click card perform click event and on second it gets focus.

anyone has idea what should I do?

Answer

I solved this few days back do I am posting here my answer if any one faeces this problem.

SparseBooleanArray did the trick in my case.

First of all declare SparseBooleanArray in your Adapter Class. and Initialize it in your constructor of adapter class.

private ArrayList<HashMap<String, String>> size;
public final SparseBooleanArray selectedItems;

public Size(ArrayList<HashMap<String, String>> title) {
    this.size = title;
    selectedItems = new SparseBooleanArray(size.size());
}

Now I use setSelected for focusing selected card. inside onBindViewHolder (or getView in case you are using BaseAdapter).

viewHolder.size.setSelected(selectedItems.get(position));
viewHolder.size.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        posSize = position;

        if (selectedItems.size() == 0) {
            selectedItems.put(position, true);
        } else if (selectedItems.size() > 0) {
            selectedItems.clear();
            selectedItems.put(position, true);
        }
        notifyDataSetChanged();
    }
});

Happy Coding.

Comments