HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Moving buttons is very slow

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
buttonsmovingslowvery

Problem

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() {
        @Override
        public void onClick(final View v) {

                // Remove the clicked button from it's frame layout parent.
                    ViewManager p = (ViewManager) v.getParent();
                    p.removeView(v);
                    // Find another button randomly.
                    Random rng = new Random();
                    View v2;
                    do
                    {
                        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();
                    p2.removeView(v2);
                    // 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.

  • Should I keep my approach but make it immediate after button click to make it faster?



  • Somehow change the properties of the buttons by swapping click listeners and images AN

Solution

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.

Context

StackExchange Code Review Q#112178, answer score: 2

Revisions (0)

No revisions yet.