【问题标题】:setmargin does not work in relative layout in androidsetmargin 在 android 的相对布局中不起作用
【发布时间】:2013-01-19 00:13:50
【问题描述】:

我以编程方式在相对布局中创建了 2 个按钮。我希望按钮之间没有边距空间,并试图通过使用“setmargin”来实现这一点,但失败了。下面是代码。

//creating the relative layout
  RelativeLayout relativeLayout = new RelativeLayout(this);
  RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);   
//creating buttons
    Button button1 = new Button(this);
    button1.setId(R.id.button1);
    RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
            SCR_W/2,
            RelativeLayout.LayoutParams.WRAP_CONTENT);//SCR_W is the device screenwidth
    params1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    params1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    params1.setMargins(0, 0, 0, 0);
    button1.setLayoutParams(params1);
    relativeLayout.addView(button1);  

    Button button2 = new Button(this);
    button2.setId(R.id.button2);
    RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
            SCR_W/2,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    params2.addRule(RelativeLayout.BELOW, button1.getId());
    params2.setMargins(0, 0, 0, 0);
    button2.setLayoutParams(params2);
    relativeLayout.addView(button2);

//setting the relative layout as the contentview
     setContentView(relativeLayout, rlp);

提前谢谢..

【问题讨论】:

    标签: android margin android-relativelayout


    【解决方案1】:

    试试这样的,它会起作用的-:

     params1.setMargins(0, 0, 0, -5);
     params2.setMargins(0, -5, 0, 0);
    

    【讨论】:

      【解决方案2】:

      我试过你的代码,对我来说还可以,

      两个按钮的距离为 0。要检查它,只需为每个按钮设置不同的颜色,您就会看到它们是在一起的。

      button1.setBackgroundColor(Color.BLUE);
      button2.setBackgroundColor(Color.RED);
      

      【讨论】:

        【解决方案3】:

        尝试将相对布局的高度设置为wrap_content..

         RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT); 
        

        【讨论】:

          猜你喜欢
          • 2014-11-08
          • 2011-12-31
          • 1970-01-01
          • 2018-05-12
          • 2014-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-21
          相关资源
          最近更新 更多