RelativeLayout以编程方式边距不起作用

时间:2015-06-08 12:25:24

标签: android relativelayout padding margins

    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正在展开,直到与作为usersPlaceholder的父LinearLayout匹配。我也尝试将填充设置为父元素,但同样的问题......

此方法转换措施

    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);
   }
}

连连呢?感谢。

2 个答案:

答案 0 :(得分:1)

LinearLayout.LayoutParamsRelativeLayout.LayoutParams都延伸MarginLayoutParams,这解释了为什么某些设置适用于两个布局。如果您设置了布局中不可用的参数,则会忽略该参数。

使用RelativeLayout时,我会使用padding代替margins。它可能会解决您的问题。

Padding直接在视图上设置,而不是在LayoutParams上设置。例如:userLay.setPadding(dp(80),dp(80),dp(80),dp(80));

答案 1 :(得分:0)

我找到了解决方案,但我不明白。我使边距有效,从LayoutParams以这种方式创建LinearLayout

LinearLayout.LayoutParams relativeParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp(80));

我没有得到它,因为我创建了一个新的RelativeLayout

RelativeLayout userlay = new RelativeLayout(mCtx);

我正在将LinearLayout参数应用于RelativeLayout

布局类型不匹配但是params有效。有人可以告诉我为什么吗?感谢。

相关问题