2
\$\begingroup\$

I have a layout with four buttons in it. I end up removing one of the buttons using:

View v = (View) findViewById(R.id.ViewId);
                    ((ViewManager) v.getParent()).removeView(v);

The problem is, whenever I remove one button (which works fine), the other three buttons move out of place.

For example, I have a top right button, a top left button, a bottom right button, and a bottom left button. I choose to remove the top right button using the code I gave earlier. This causes all the other three buttons to move out of place.

I think this may be because of the xml, where it states things like:

android:layout_toRightOf

And I think that when I move one button, that statement in the xml has nothing to be to the right of, and so it goes of to a random position. Is there a way I can remove these statements without having to change the position of my buttons?

Can I keep the buttons independent of each-other?

\$\endgroup\$
1
\$\begingroup\$

I think this is what you want. It makes the button invisible while still being used for layout. That way it will still take out the same space and not change your layout.

View b = findViewById(R.id.your_button);
b.setVisibility(View.INVISIBLE);
\$\endgroup\$
  • \$\begingroup\$ Great answer, but there is one problem. I end up replacing that part of the button with another button...How should I approach this. I'm not sure if I'm even replacing the button correctly...What should I do to replace it? I was thinking of getting the exact coordinates of the button, and then putting a new button there \$\endgroup\$ – NullPointerException Nov 26 '15 at 7:09
  • \$\begingroup\$ What should I do? \$\endgroup\$ – NullPointerException Nov 26 '15 at 7:14
  • \$\begingroup\$ @NullPointerException Well that's outside the scope of your original question. Also I'm not sure the getting the exact coordinates approach is the best. Feels like just sticking a stickier on it. It wouldn't really be a part of the layout. I don't know why you would need to change the button, but you could either keep the button and just change the name and maybe the OnClickListener. If that isn't good enough, then put the buttons in different FrameLayouts. Then simply remove the original button like before and put the new button in the FrameLayout that held that button. \$\endgroup\$ – Christer Nov 26 '15 at 7:37
  • \$\begingroup\$ @NullPointerException I just answered a similar question related to how to swap two buttons on android. It might help. gamedev.stackexchange.com/a/111982/75055 If any of this helped answer your question it would be nice if you marked the answer as accepted. \$\endgroup\$ – Christer Nov 26 '15 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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