[英]horizontalscrollview set child elements to fill horizontalscrollview width
[英]How to set width of LinearLayout (with 7 TextView Elements), which is a child of HorizontalScrollView, so that only 4 are visible at a time?
我在HorizontalScrollView中有一个LinearLayout(带有7个TextView元素)。 HorizontalScrollView设置为fillViewport。 我希望一次仅显示4个TextView元素。 用户可以滚动查看其余部分。
情况1:我可以使用layout_weight获得所需的布局,但随后无法滚动,如随附的代码所示。 我假设滚动不起作用,因为权重是在GUI渲染后计算的,因此HorizontalScrollLayout的宽度不会改变。 那正确吗?
情况2:如果我固定宽度,例如“ 60dp”,则它会根据需要显示,并且我也可以滚动。 但是,这不适用于其他屏幕尺寸。
如何以与不同屏幕尺寸配合使用的方式实现此效果。
这是案例1的代码。
布局:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="7">
<TextView
style="@style/ViewStyle"
android:text="1" />
<TextView
style="@style/ViewStyle"
android:text="2" />
<TextView
style="@style/ViewStyle"
android:text="3" />
<TextView
style="@style/ViewStyle"
android:text="4" />
<TextView
style="@style/ViewStyle"
android:text="5" />
<TextView
style="@style/ViewStyle"
android:text="6" />
<TextView
style="@style/ViewStyle"
android:text="7" />
</LinearLayout>
样式:
<style name="ViewStyle">
<item name="android:layout_weight">1</item>
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">60dp</item>
<item name="android:layout_centerVertical">true</item>
<item name="android:layout_centerHorizontal">true</item>
<item name="android:gravity">center</item>
<item name="android:textSize">10sp</item>
<item name="android:textColor">@color/white</item>
</style>
在HorizontalScrollView
包装的LinearLayout
使用layout_weight
并不能很好地满足您的需求。 我建议你做这样的事情:
style
删除layout_weight
属性,还可以将layout_width
修改为一个值(或者您可以使用wrap_content
) 在onCreate
方法中的一个视图上发布一个Runnable
,以更新TextViews
的文本,如下所示:
// wrapperLinearLayout being your LinearLayout wrapping the 7 TextViews wrapperLinearLayout.post(new Runnable() { @Override public void run() { // find out the width of the HorizontalScrollView HorizontalScrollView hsv = (HorizontalScrollView) wrapperLinearLayout .getParent(); // the value below will be the new width of all the TextViews so // you can see only for initially int targetWidth = (hsv.getWidth() / 4) * 7; // modify the width of all 7 TextViews for (int i = 0; i < wrapperLinearLayout.getChildCount(); i++) { LinearLayout.LayoutParams lpc = (android.widget.LinearLayout.LayoutParams) wrapperLinearLayout .getChildAt(i).getLayoutParams(); lpc.width = targetWidth / 7; } } });
您必须在运行时获取屏幕宽度,然后为textview设置宽度。 我想那是让它正常工作的唯一方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.