2011-07-14 135 views
0

我正在尝试创建类似于主屏幕布局的内容。它包含多个垂直方向的LinearLayout,位于一个水平方向的LinearLayout中,全部位于Horizo​​ntalScrollView中。我把它写成了一个名为'HomeLayout'的扩展Horizo​​ntalScrollView的自定义类。Android:将布局添加到Horizo​​ntalScrollView

hierarchyviewer

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

的问题是 '画面2' 具有宽度 '0' 添加时。

这只适用于如果我在onDraw()中调用此方法,并使用getMeasuredWidth()和getMeasuredHeight()而不是LayoutParams.FILL_PARENT。即使如此,我不确定这是否正确。

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

我松散遵循此链接:http://blog.velir.com/index.php/2010/11/17/android-snapping-horizontal-scroll/

我在做什么错?

回答

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); 
} 
相关问题