android-studiofor-looponlongclicklistener

How to make a loop rerun from onLongClick()?


Here is the code. If a View has been long clicked, I want this loop to rerun by making i = 0. But the if statement after setOnLongClickListener only gets executed once in the beginning and not after the view has been long clicked.

final hasLongClicked[] = {false};
for(int i = 0; i < mLLayout.getChildCount(); i++){
                // tried declaring hasLongClicked[] here but no avail
                View child = mLLayout.getChildAt(i);
                child.setOnLongClickListener(new View.OnLongClickListener(){
                    @Override
                    public boolean onLongClick(View v) {
                        //Some stuff
                        hasLongClicked[0] = true;
                        return false;
                    }
                });
                if(hasLongClicked[0])
                    i = 0;
        
            }

How do I do get through this? On a separate note, is this a good way to setOnLongClickListeners to all child views of a linear layout?

Help is much appreciated. Thank you


Solution

  • I solved it by making a function out of it and calling itself whenever the event has been handledas follows:

        private void discardEvents(LinearLayout mLLayout) {
        for(int i = 0; i < mLLayout.getChildCount(); i++){
            View child = mLLayout.getChildAt(i);
            child.setOnLongClickListener(new View.OnLongClickListener(){
                @Override
                public boolean onLongClick(View v) {
                    //Do your stuff
                    discardEvents(mLLayout);
                    return false;
                }
            });
        }
    }
    

    Although I would like to know if this would cause any problems/ has hidden bugs.