【问题标题】:RelativeLayout programmatically margins not workingRelativeLayout 以编程方式边距不起作用
【发布时间】:2015-08-22 22:01:34
【问题描述】:
    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);
   }
}

建议?谢谢。

【问题讨论】:

  • 不要调用 requestLayout() 系统会为你调用
  • 好的,谢谢,我打电话给它是因为我读到它可能是一个解决方案,但是无论调用还是不调用都不能使边距起作用:/
  • 分享更多代码。这段代码非常简单,我不在这里。 Main.lay_found_useres。分享这个观点
  • Main 是主要的 Activity,lay_found_users 只是父 LinearLayout 声明为静态的。分享更多代码。

标签: android android-relativelayout padding margins


【解决方案1】:

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

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

我不明白,因为我创建了一个新的RelativeLayout

RelativeLayout userlay = new RelativeLayout(mCtx);

我将LinearLayout 参数应用于RelativeLayout

布局类型不匹配,但参数有效。有人能告诉我为什么吗?谢谢。

【讨论】:

    【解决方案2】:

    LinearLayout.LayoutParamsRelativeLayout.LayoutParams都扩展了MarginLayoutParams,这解释了为什么某些设置适用于这两种布局。如果您设置的参数在布局中不可用,则它会被忽略。

    当使用RelativeLayout 时,我会使用padding 而不是margins。它可能会解决您的问题。

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

    【讨论】:

    • 感谢您的回答。我现在明白了!
    猜你喜欢
    • 2017-01-17
    • 2013-12-17
    • 1970-01-01
    • 2011-12-27
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    相关资源
    最近更新 更多