簡體   English   中英

Android獲取並設置布局寬度

[英]Android get and set layout width

<HorizontalScrollView
    android:id="@+id/horizontalScrollView1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:fillViewport="true"
    android:layout_weight="19" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <LinearLayout
            android:id="@+id/layoutScrollContainer"
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="@drawable/card_background" >

           <
            .
            .
            .
            .
            .
            .
            />
        </LinearLayout>


    </LinearLayout>
</HorizontalScrollView>

我想獲取HorizontalScrollView1的寬度並將其設置為LinearLayoutlayoutScrollContainer

這是我在Java中的代碼,但是我的應用程序崩潰了,我不明白為什么。 如果您知道如何使用xml進行操作,請告訴我。

HorizontalScrollView scrollView = (HorizontalScrollView) findViewById (R.id.horizontalScrollView1);
    LinearLayout lrLayout = (LinearLayout ) findViewById (R.id.layoutScrollContainer);

    int  width = scrollView.getMeasuredWidth();
    lrLayout.setLayoutParams(new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MATCH_PARENT));

所以...您尚未為線性圖層定義任何ID。 檢查一下:

 LinearLayout lrLayout = (LinearLayout ) findViewById (R.id.llayoutContainer1);

只需為線性布局設置ID:D

它崩潰,因為LayoutParams始終引用父對象。 在您的情況下,您將收到ClassCastException因為您使用的是LinearLayout.LayoutParams

我知道這很舊,但是我碰到了它並得到了答案。

崩潰可能是因為您在繪制或測量元素之前在onCreate執行了此操作。

解決此問題的最佳方法是使用ViewTreeObserver並且在繪制布局后,可以重置寬度:

您如何知道何時繪制了布局?

特別是,在onCreate之后,在測量視圖之前, scrollView.getMeasuredWidth()將不起作用

暫無
暫無

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

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