如何设置LinearLayout的宽度(与7 TextView元素),这是一个孩子的HorizontalScrollVi



我有一个LinearLayout(与7 TextView元素),在一个HorizontalScrollView。HorizontalScrollView设置为fillViewport。我想只有4个TextView元素是可见的一次。用户可以滚动查看其余内容。

案例1:我能够使用layout_weight获得所需的布局,但随后我无法滚动,如所附代码所示。我假设滚动不起作用,因为权重是GUI渲染后计算的,所以HorizontalScrollLayout的宽度不会改变。对吗?

案例2:如果我固定宽度,例如"60dp",那么它就会按要求显示,我也可以滚动。但是,这在其他屏幕尺寸上不起作用。

我怎样才能在不同的屏幕尺寸下实现这个效果呢?

下面是Case 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>

LinearLayout中使用layout_weight包裹在HorizontalScrollView中不会很好地达到您想要的效果。我建议你这样做:

  1. style中删除layout_weight属性,也将layout_width修改为一个值(或者您可以使用wrap_content)
  2. 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;
            }
        }
    });
    

你必须在运行时获得屏幕宽度,然后为你的textviews设置宽度。我想这是唯一能让它工作的方法。

相关内容

最新更新