Backspace
Backspace

Reputation: 302

how to place buttons on a layout based on condition?

I am creating an android layout in which I will place 3 buttons vertically with some space between them. But based on the requirements, the button count can come down to 2, and I need the buttons to repositioned based on the available screen space.See the screens below.

3 buttons

now the second case with two buttons should be like

2 buttons

How should I go about doing this ?

Upvotes: 0

Views: 56

Answers (3)

Subhan Ali
Subhan Ali

Reputation: 1430

You can just set visibility of buttons depending upon your condition just like the following:

button.setVisibility(View.GONE);

When you set visibility to gone then the space will considered available for other layouts and your will be set as per your desire.

When you set visibility to invisible then the space will considered as allocated.

Upvotes: 1

from56
from56

Reputation: 4127

You can define all three buttons in the layout XML and then :

if you want to show the third button

 thirdButton.setVisibility(View.VISIBLE);

if you want to hide

 thirdButton.setVisibility(View.GONE);

at least if using a Linear or Relative Layout it should repositione by itself.

Upvotes: 0

Sandeep dhiman
Sandeep dhiman

Reputation: 1921

You can try below code for achieving the same based on your condition for adding buttons to your layout

//the layout on which you are working
LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout_tags);

//set the properties for button
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setText("Button");
btnTag.setId(some_random_id);

//add button to the layout
layout.addView(btnTag);

Upvotes: 0

Related Questions