Owen Nel
Owen Nel

Reputation: 417

Android: Align a Button to the Right in LinearLayout

I have a piece of code which I use to create a new LinearLayout. Within the layout I wish to add a TextView which contains both a label and a value. Then next to it on the right I want to display the button. I want the button to be located toward the end of the screen, without stretching the button. I am happy with the button width and height as WARP_CONTENT.

How can I achieve this in code? I have barely any XML so using XML is not an option. I am trying to make the app as dynamic as possible, so I decided to steer clear of XML.

Please see the code below:

    // Build a button
    final Button addButton = new Button(task.getParent());
    addButton.setText("Add New");
    addButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // Open a file picker here to let the user pick a file
        }
    });

    // Build a new layout to hold all the elements
    LinearLayout verticalLayout = new LinearLayout(task.getParent());
    verticalLayout.setOrientation(LinearLayout.HORIZONTAL);
    verticalLayout.addView(sizeTextView);
    verticalLayout.addView(addButton);

Thank you guys in advance.

Upvotes: 1

Views: 1181

Answers (3)

LHA
LHA

Reputation: 9655

Try this: Add Space (View) between TextView & Button.

    // View space = new View(parent_context);
    View space = new View(task.getParent());

    // Width:0dp, Height:1 & Weight: 1.0
    LinearLayout.LayoutParams spaceLP = new LinearLayout.LayoutParams(0, 1, 1.0f);
    space.setLayoutParams(spaceLP);

    verticalLayout.addView(sizeTextView);

    verticalLayout.addView(space);

    verticalLayout.addView(addButton);

Upvotes: 2

Awadesh
Awadesh

Reputation: 4068

To achieve this you should use Relative layout and RelativeLayout.LayoutParams. By using LayoutParams you can set the rule to align your views as per your requirements.

for example

RelativeLayout.LayoutParams params =  (RelativeLayout.LayoutParams)button.getLayoutParams();
 params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
 params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);
  button.setLayoutParams(params); 

Upvotes: 0

starkshang
starkshang

Reputation: 8558

Add textview with size and gravity,like this:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.setLayoutDirection(Gravity.RIGHT|Gravity.CENTER_VERTICAL);      
verticalLayout.addView(sizeTextView,params);

Upvotes: 0

Related Questions