0

我正在尝试创建类似于主屏幕布局的东西。这由单个水平方向的 LinearLayout 中的多个垂直方向的 LinearLayout 组成,所有这些都位于 Horizo​​ntalScrollView 中。我将其编写为一个名为“HomeLayout”的自定义类,它扩展了 Horizo​​ntalScrollView。

层次查看器

LinearLayout wrapper = new LinearLayout(getContext());
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
wrapper.setLayoutParams(params);
wrapper.setOrientation(LinearLayout.HORIZONTAL);

addView(wrapper);

for(int i = 0; i < 2; i++) {
    LinearLayout linear = (LinearLayout) View.inflate(getContext(), R.layout.screens, null);    
    linear.setLayoutParams(params);

    wrapper.addView(linear);
}

问题是添加时“screen2”的宽度为“0”。

这只适用于我在 onDraw() 中调用它并使用 getMeasuredWidth() 和 getMeasuredHeight() 而不是 LayoutParams.FILL_PARENT。即使那样,我也不确定这是否是正确的做法。

此外,我无法在 onCreate() 中引用视图 'wrapper'、'screen1'、'screen2'。

我松散地遵循了这个链接:http ://blog.velir.com/index.php/2010/11/17/android-snapping-horizo​​ntal-scroll/

我究竟做错了什么?

4

1 回答 1

0

希望这对其他人有所帮助。我通过以下方式实现 onMeasure() 解决了我的问题:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    setMeasuredDimension(width, height);

    for(int i = 0; i < mWrapper.getChildCount(); i++) {
        View child = mWrapper.getChildAt(i);
        child.setLayoutParams(new LinearLayout.LayoutParams(width, 
        LayoutParams.FILL_PARENT));
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
于 2011-07-15T07:20:31.723 回答