簡體   English   中英

在水平滾動視圖中設置線性布局的寬度

[英]set width of linear layout in horizontal scroll view

我具有以下線性布局,並將其設置為Horizo​​ntalScrollView的子級

文件menu.xml

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/menu"
android:orientation="vertical" android:background="#2f4f4f" android:layout_width="wrap_content" android:layout_height="fill_parent">

  <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:background="#2f4f4f" android:cacheColorHint="#2f4f4f" android:scrollbars="none">
  </ListView>
</LinearLayout>

文件:scrollview.xml

 <?xml version="1.0" encoding="utf-8"?>
 <HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#00ffffff" android:padding="0px"
android:layout_margin="0px" android:fadingEdge="none" android:fadingEdgeLength="0px" android:scrollbars="none">
    <LinearLayout android:id="@+id/top" android:layout_height="fill_parent" android:layout_width="fill_parent"
    android:orientation="horizontal" android:background="#ffffffff" android:padding="0px" android:layout_margin="0px">
    </LinearLayout>
</HorizontalScrollView>

我正在嘗試以編程方式設置線性布局的寬度,但是卻收到ClassCastException。(LinearLayout $ LayputParams無法轉換為FrameLayout $ LayputParams)

LayoutInflater inflater = LayoutInflater.from(this);
scrollView = inflater.inflate(R.layout.scrollview_xml, null);
setContentView(scrollView);
View menu = inflater.inflate(R.layout.menu_xml, null);
scrollView.addView(menu);
scrollView.getChildAt(0).setLayoutParams(new ViewGroup.LayoutParams(100,100));

如何解決呢?

  1. 由於scrollView擴展了FrameLayout,因此您需要將其子級的layoutParams設置為具有FrameLayout的layoutParams。

  2. 因為它說您有異常是因為您為錯誤的布局設置了layoutParams,所以請使用正確的布局:

    scrollView.getChildAt(0).setLayoutParams(new FrameLayout .LayoutParams(100,100));

  3. 通常,如果您對布局的類型有疑問,請使用:

    scrollView.getChildAt(0).setLayoutParams(new ViewGroup .LayoutParams(100,100));

當您可以直接使用它們時,為什么要類型轉換layoutParams,

scrollView.getChildAt(0).setLayoutParams(new LayoutParams(100,100));

暫無
暫無

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

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