Reputation: 11
When I try to set a margin with this code:
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
RelativeLayout.LayoutParams params;
TextView login = (TextView) findViewById(R.id.textView2);
int text_height = login.getHeight();
int text_whidth= login.getWidth();
params = new RelativeLayout.LayoutParams((int)login.getLayoutParams().WRAP_CONTENT, (int)login.getLayoutParams().WRAP_CONTENT);
params.setMargins(0, 500, 0, 0);
login.setLayoutParams(params);
}
The app crashes on start. How can I set margin without it crashing my app?
Thanks for your help.
Upvotes: 0
Views: 7710
Reputation: 3926
here is Method for you, just need to pass parameters
public static void setMargin(View view, int left, int right, int top, int bottom) {
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)
view.getLayoutParams();
params.setMargins(left, top, right, bottom);
view.setLayoutParams(params);
}
where First Parameter view is Your TextView.
Upvotes: 1
Reputation: 1150
LayoutParams having setMargins
method and then set params to setLayoutParams()
method of TextView
.
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10,10,10,10); // setMargins(left, top, right, bottom)
textView.setLayoutParams(params);
Upvotes: 0
Reputation: 3381
Try to replace the following line:
params = new RelativeLayout.LayoutParams((int)login.getLayoutParams().WRAP_CONTENT, (int)login.getLayoutParams().WRAP_CONTENT);
with this one:
params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
Upvotes: 2