Tuesday, February 11, 2020

java - Swap buttons in layout


Say I have 4 buttons. I want to have button 2 always swap out with another button, randomly. So, when the user taps button 2, it should swap with another button (randomly).


Now, button 2 is at the bottom right corner. So if the user taps button 2 again, it has the option to swap with the other three buttons. How can I achieve this?


I have already tried to make an array of the four values:


top_right, top_left, bottom_right, bottom_left

And have successfully had them swap, but it was very memory inefficient, and took a while.




Answer



I created a working demo using android's built-in buttons.


This is the main Activity class. Each button have the same onClick method buttonClicked().


List buttons = new ArrayList();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


// Store the button to the buttons array for later.
buttons.add(findViewById(R.id.button));
buttons.add(findViewById(R.id.button2));
buttons.add(findViewById(R.id.button3));
buttons.add(findViewById(R.id.button4));
}


public void buttonClicked(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());
p2.addView(v, v.getLayoutParams());
}


This is how the layout looks like. I have each button in a separate frame layout which stay where they are with the buttons inside swapping which frame container they are inside.


enter image description here


If anything is unclear just ask.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...