[英]Android: Adding Layouts to HorizontalScrollView
我正在嘗試創建類似於主屏幕布局的東西。 這由單個水平方向的 LinearLayout 中的多個垂直方向的 LinearLayout 組成,所有這些都位於 HorizontalScrollView 中。 我將其編寫為自定義 class,稱為“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/
我究竟做錯了什么?
希望這對其他人有所幫助。 我通過以下方式實現 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.