簡體   English   中英

如何設置LinearLayout(帶有7個TextView元素)的寬度(這是Horizo​​ntalScrollView的子級),以便一次只能看到4個?

[英]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?

我在Horizo​​ntalScrollView中有一個LinearLayout(帶有7個TextView元素)。 Horizo​​ntalScrollView設置為fillViewport。 我希望一次僅顯示4個TextView元素。 用戶可以滾動查看其余部分。

情況1:我可以使用layout_weight獲得所需的布局,但隨后無法滾動,如隨附的代碼所示。 我假設滾動不起作用,因為權重是在GUI渲染后計算的,因此Horizo​​ntalScrollLayout的寬度不會改變。 那正確嗎?

情況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並不能很好地滿足您的需求。 我建議你做這樣的事情:

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

您必須在運行時獲取屏幕寬度,然后為textview設置寬度。 我想那是讓它正常工作的唯一方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM