[英]RelativeLayout programmatically margins not working
LinearLayout usersPlaceholder = Main.lay_found_users; //Found Users Placeholder
//RelativeLayout Params
RelativeLayout userlay = new RelativeLayout(mCtx); //Create new Element
userlay.setBackgroundResource(R.drawable.btn_useritem); //Background
userlay.setGravity(RelativeLayout.CENTER_HORIZONTAL); //Gravity
userlay.setClickable(true); //Clickable
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, dp(80));
relativeParams.setMargins(dp(80), dp(80), dp(80), dp(80));
userlay.setLayoutParams(relativeParams);
userlay.requestLayout();
usersPlaceholder.addView(userlay);
边距未设置。 作为子元素的RelativeLayout
一直在扩展,直到匹配作为LinearLayout
的父usersPlaceholder
为止。 我还尝试将填充设置为父元素,但存在相同的问题...
这种方法改变了措施
public int dp(int dps){
final float scale = mCtx.getResources().getDisplayMetrics().density;
return (int) (dps * scale + 0.5f);
}
主要活动:
public class Main extends Activity{
Context ctx;
public static LinearLayout lay_found_users;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
lay_found_users = (LinearLayout) findViewById(R.id.lay_found_users);
}
}
建议? 谢谢。
LinearLayout.LayoutParams
和RelativeLayout.LayoutParams
扩展了MarginLayoutParams
,这解释了为什么某些设置同时应用于这两个布局。 如果设置的参数在布局中不可用,则将被忽略。
使用RelativeLayout
,我将使用padding
而不是margins
。 它可能会解决您的问题。
Padding
直接在视图上设置,而不是在LayoutParams
。 因此,例如: userLay.setPadding(dp(80),dp(80),dp(80),dp(80));
我找到了解决方案,但我不明白。 我完成了边距工作,以这种方式从LinearLayout
创建LayoutParams
:
LinearLayout.LayoutParams relativeParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp(80));
我没有得到它,因为我创建了一个新的RelativeLayout
:
RelativeLayout userlay = new RelativeLayout(mCtx);
我正在将LinearLayout
参数应用于RelativeLayout
布局类型不匹配,但参数有效。 有人可以告诉我为什么吗? 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.