以编程方式添加的android视图组之间的不需要的间距

时间:2015-04-16 18:32:41

标签: android android-layout

我在RelativeLayout中添加FrameLayout(以xml格式添加),并在此RelativeLayout中附加LinearLayout

问题是我在RelativeLayout和它的子LinearLayout之间得到了一个不需要的左/右间距/填充,正如你可以从uiautomator转储中看到的那样。 奇怪的是,在模拟器N5,N4,N7图像和Moto G和N4设备上测试的每侧的间距总是 11个像素。 谢谢

enter image description here

代码是:

       rlBottomBarContainer = new RelativeLayout(this);
    rlBottomBarContainer.setId(R.id.bottomBarContainer);
    rlBottomBarContainer.setClipToPadding(false);
    rlBottomBarContainer.setClipChildren(false);
    rlBottomBarContainer.setBackground(getResources().getDrawable(R.drawable.bara));

    int topMargin = whiteTowerContainerHeight /2 + tower_height/2 + 100;
    int containerHeight = whiteTowerContainerHeight - topMargin;
    FrameLayout.LayoutParams containerParams = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT,
             containerHeight);
    containerParams.topMargin = topMargin;

    rlBottomBarContainer.setLayoutParams(containerParams);
    frameLayoutRoot.addView(rlBottomBarContainer);     // parentLayout

    llBottomBarContainer = new LinearLayout(this);
    llBottomBarContainer.setId(R.id.upper_bottombar_ID);
    llBottomBarContainer.setClipChildren(false);
    llBottomBarContainer.setClipToPadding(false);
    llBottomBarContainer.setBackgroundColor(Color.parseColor("#00FFFFFF"));
    llBottomBarContainer.setOrientation(LinearLayout.HORIZONTAL);

    RelativeLayout.LayoutParams bottomBarParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
             getBottomBarTextSize());

    llBottomBarContainer.setLayoutParams(bottomBarParams);
    rlBottomBarContainer.addView(llBottomBarContainer);

从代码中可以看出,LinearLayout添加了match_parent作为宽度。 RelativeLayout宽度为0到720px,但LinearLayout为11到709像素。

1 个答案:

答案 0 :(得分:0)

首先,我不明白为什么你使用FrameLayout而你不直接使用RelativeLayout作为父布局。

我在您的代码中看到的错误是您将FrameLayout.LayoutParams设置为RelativeLayout,将RelativeLayout.LayoutParams设置为LinearLayout。 可能这就是为什么你得到一些额外的间距。

我建议您不要以编程方式创建布局,而是在xml上创建布局,然后如果需要java上的布局对象,可以使用findViewById(int id)方法获取它们