我正在尝试创建类似于主屏幕布局的内容。它由一个水平定向的LinearLayout中的多个垂直方向的LinearLayout组成,所有这些都位于HorizontalScrollView中。我把它写成了一个名为'HomeLayout'的自定义类,扩展了HorizontalScrollView。
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-horizontal-scroll/
我做错了什么?
答案 0 :(得分: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);
}