I have a very simple app which removes buttons and re-adds buttons to certain layouts when a button is clicked. The problem is this process is taking a very long time. How do I speed this process up?

red.setOnClickListener(new View.OnClickListener() {
        public void onClick(final View v) {

                // Remove the clicked button from it's frame layout parent.
                    ViewManager p = (ViewManager) v.getParent();
                    // Find another button randomly.
                    Random rng = new Random();
                    View v2;
                        int i = rng.nextInt(4);
                        v2 = buttons.get(i);
                    while (v2 == v); // Loop until you get a different button to swap with.
                    // Remove the other button from it's frame layout parent.
                    ViewManager p2 = (ViewManager) v2.getParent();
                    // Now simply insert each button into the other buttons frame layout.
                    p.addView(v2, v2.getLayoutParams()); //Adding v2, the random button, into where v, the button clicked, was before(p)!
                    p2.addView(v, v.getLayoutParams()); //Adding v, the button clicked, into where v2, the random button, was before(p2)

This code just gets another button from the other three (there are 4 buttons in total) randomly, and swaps the red button (the button clicked) with the random button.

The problem is this process is taking 3-4 seconds after being clicked How can I speed it up? I want it to appear as if the buttons have been swapped as soon as the red button is clicked.

  1. Should I keep my approach but make it immediate after button click to make it faster?
  2. Somehow change the properties of the buttons by swapping click listeners and images AND somehow being able to keep track of the NEW red button so that I can swap again.
  • 2
    \$\begingroup\$ Could you provide some more context, such as the code for setting up the buttons, or the view XML or anything? \$\endgroup\$ Nov 28, 2015 at 21:36

1 Answer 1


Loop could be removed. Replace with collection or array with each button choice. Remove the element clicked from collection. Use Random to choose an index or key of another remaining button.

Instance variable could retain which button last clicked.

Cast of v2.getParent and the ViewManager could instead be held as references in instance variables and quickly retrieved from a collection.

If Swing, could look at using awt directly for increased performance.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.