Home > OS >  How can i unselect an item if another item is selected?
How can i unselect an item if another item is selected?

Time:09-22

enter image description here

I am having some Views..I want that if one item is selected the other should get unselected automatically. And when (as shown in image) , if suppose 2nd item whose text here is 100 is selected , the first selection should get unselected. How can i keep a reference of the selected item and unselect other item?? Somewhere i came to know about radio button is used in these..but how can someone show this?

CodePudding user response:

Whenever you call your "select" method, inside the code it should first clear any selections you have that are previously existing. You can do this by checking the property / state of every eligible selection and then reversing what you did to select it. You can also keep a reference to the current selection as a sort of hack, and just keep updating that and using it to deselect when a new selection is made.

CodePudding user response:

Assuming that you mean changing background etc. by "selecting", you can iterate over the parent ViewGroup (e.g. ConstraintLayout, LinearLayout etc.) and select your target view and unselect the rest of views like the following code.

void toggleView(View view, boolean selected) {
    if (selected) {
        view.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(getContext(), R.color.bg_grey_2)));
    } else {
        view.setBackgroundTintList(null);
    }
}

void selectOneViewAndUnselectOthers(ViewGroup parentView, View viewToSelect) {
    for (int i = 0; i < parentView.getChildCount(); i  ) {
        View tmpView = parentView.getChildAt(i);
        if (tmpView.getId() == viewToSelect.getId()) {
            toggleView(viewToSelect, true);
        } else {
            toggleView(tmpView, false);
        }
    }
}
  • Related