1

Can I set the position of the widget with programming in android instead the xml code. For example:

enter image description here

And like these. Are there methods instead the above xml code to use?

and
  • 341
  • 1
  • 3
  • 11
  • Duplicate http://stackoverflow.com/questions/5191099/how-to-set-relativelayout-layout-params-in-code-not-in-xml – Breavyn Sep 05 '15 at 12:09

2 Answers2

0

Yes you can, for example

Button button1 = new Button(R.id.buttonn);
Button button2 = new Button(R.id.buttonn2);
button1.setX(button2.getX);

There are more functions like setX , if you need something spesificly just ask for it :)

DavidBalas
  • 333
  • 7
  • 21
0

Yes you can set all the circled attributes via code aswell. For example this code aligns the button1 to the left of its parent (RelativeLayout) and positions button2 left of button1.

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
button1.setLayoutParams(params);

params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, button1.getId());
button2.setLayoutParams(params);

Keep in mind that

  • layout_alignTop
  • layout_alignEnd
  • layout_alignParentBottom
  • layout_alignParentLeft
  • layout_alignParentStart
  • layout_toRightOf
  • layout_above
  • layout_below
  • layout_centerInParent
  • layout_centerHorizontal

will work only if the view you are setting the attributes to, is inside a RelativeLayout.

Original answer,

Community
  • 1
  • 1
Marko
  • 20,385
  • 13
  • 48
  • 64