3

How to set margin in relative layout with code (not XML)?

I use this code but nothing happened:

RelativeLayout rlDetail = new RelativeLayout(context);
rlDetail.setBackgroundResource(R.drawable.bg_round);
RelativeLayout.LayoutParams rlDetailParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rlDetailParams.setMargins(35, 10, 35, 0);
rlDetail.setLayoutParams(rlDetailParams);
Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
Frank Junior
  • 575
  • 1
  • 9
  • 19

1 Answers1

0

try this answer set the absolute position of a view in Android

as mentioned in the link above you should use

TextView tv1 = new TextView(context);

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = needed_margin;
params.topMargin = needed_margin;

// add your textview like this
rl.addView(tv1, params);
Community
  • 1
  • 1
ColdFire
  • 6,764
  • 6
  • 35
  • 51
  • how are you adding views to this layout? follow the example on the link to add views.. – ColdFire Oct 22 '12 at 10:42
  • RelativeLayout rlDetail = new RelativeLayout(context); rlDetail.setBackgroundResource(R.drawable.bg_round); RelativeLayout.LayoutParams rlDetailParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); rlDetailParams.setMargins(35, 10, 35, 0); rlDetail.setLayoutParams(rlDetailParams); TextView tv1 = new TextView(context); tv1.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)); tv1.setText("Test"); rlDetail.addView(tv1); – Frank Junior Oct 22 '12 at 10:46
  • try adding the views like mentioned in the example from the link.. check my updated answer – ColdFire Oct 22 '12 at 10:50
  • i want set margin for relaltivelayout not the textview – Frank Junior Oct 22 '12 at 10:52
  • this way the parameter are set for the `RelativeLayout` rl and then used to add the `TextView`.. – ColdFire Oct 22 '12 at 10:54