Custom checkbox class in android

I needed to map checkboxes to their position in the list view in the checkbox's onClickListener. My first solution was to make a very short custom view that extended the checkbox but had an additional variable (position) to 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 that it changed the color of the checkboxes to black and nothing I did (including changing android: buttonTint) could change it. At the moment my solution is a HashMap with a view key and an 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 was would be very grateful.

+3


source to share


1 answer


You can use setTag () method to pass an extra variable to the view, then you can use getTag () to get an extra variable. It doesn't need to customize the CheckBox.



//set tag
checkBox.setTag(position);

//get tag
int position = (int)checkBox.getTag();

      

+1


source







All Articles