在水平滚动视图中设置线性布局的宽度

时间:2012-12-29 08:24:12

标签: android android-layout horizontalscrollview

我有以下线性布局,我将其设置为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));

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

为什么要直接使用layoutParams进行类型转换,

scrollView.getChildAt(0).setLayoutParams(new LayoutParams(100,100));
相关问题