Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom checkbox class in android

I needed to correlate checkboxes with their position in the list view in the checkboxes' onClickListener. My first solution was to make a very short custom view that extended checkbox but had an extra variable (position) that would be set in getView().

    public class ListCheckBox extends CheckBox {
    private int position = -1;

   public ListCheckBox(Context context)
   {super(context);}
   public ListCheckBox(Context context, AttributeSet attrs)
   {super(context,attrs);}
   public ListCheckBox(Context context, AttributeSet attrs, int defStyleAttr)
   {super(context,attrs,defStyleAttr);}
    @TargetApi(21)
    public ListCheckBox(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
   {super(context,attrs,defStyleAttr,defStyleRes);}

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }
}

It worked, except it changed the checkboxes' color to black, and nothing I did (including changing android:buttonTint) could change it. For now my solution is a HashMap with a view key and integer value that keeps track of the checkboxes' and their positions, but if anyone has a less ugly solution or any idea as to why I couldn't change the color of the checkboxes, it would be very much appreciated.

like image 429
user2407621 Avatar asked Feb 21 '26 22:02

user2407621


1 Answers

You can use the method of setTag() to past a extra variable to a view,then you can use getTag() to get the extra variable. This does not need to custom CheckBox.

//set tag
checkBox.setTag(position);

//get tag
int position = (int)checkBox.getTag();
like image 187
anseey Avatar answered Feb 23 '26 10:02

anseey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!