Check if an element exists inside an Array

1

It turns out that I'm doing an app that contains a list that is launched from CustomDialog . When selecting one or more of its items I save the ID's in an array, thus leaving [1, 3, 5, 6] . With a "Cancel" button the ArrayList is cleared and the dialog is closed.

deleteIds.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    myArrayList.clear();
                    dialogView.dismiss();
                }
            });

The problem comes with the other button that is "Save" whose action is only to close the dialog so the list stays loaded with the elements that I selected. The point is that when you reopen the dialog and choose an item that you had already loaded before, the list stays like this: [1, 1, 3, 5, 6] . Is there any way to imply that it has already been marked? How do I verify if that item I selected again is already loaded in the list?

I was thinking of something similar to giving it a different color within setOnItemClickListener .

view.setBackgroundColor(Color.parseColor("#ADD8E6"));

I have been told that I can leave the ones I already have selected in the list painted in a different color, but I do not know how to do it. I hope you can help me and thanks in advance!

    
asked by Megaherx 02.08.2018 в 23:35
source

1 answer

0

Instead of using an arrayList you can use a Set type set, such as a HashSet. Set is an interface that is used to represent collections where no element can be repeated. HashSet is a class that inherits from Set. You can instantiate the object in this way:

Set<Integer> iDs = new HashSet<>();

Set has the add method, which returns a boolean. If it returns true, it is that the element could be added; if it returns false it is that the element already exists in the set and you can not add it.

This way you will not be able to have repeated elements in your set of ID's.

If you also want items that are on the list can not be re-selected test with

item.setEnable(false);

You go through your list of ID's and all of them exist put them to false, or give them a different appearance.

    
answered by 03.08.2018 в 00:21