[英]Android set margin of textview programmatically
当我尝试使用此代码设置边距时:
@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);
}
该应用程序在启动时崩溃。 如何设置保证金而不会使我的应用程序崩溃?
谢谢你的帮助。
尝试替换以下行:
params = new RelativeLayout.LayoutParams((int)login.getLayoutParams().WRAP_CONTENT, (int)login.getLayoutParams().WRAP_CONTENT);
与此:
params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
这是给您的方法,只需要传递参数
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);
}
其中第一个参数视图是您的TextView。
具有setMargins
方法的LayoutParams,然后将参数设置为TextView
setLayoutParams()
方法。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.