【发布时间】:2011-07-22 23:12:17
【问题描述】:
我在 Android 中有一个 HorizontalScrollView,在 xml 中如下所示。
<com.se.myapp.MyScroller
android:layout_width="fill_parent"
android:layout_height="110dp"
android:scrollbars="none">
<LinearLayout
android:id="@+id/scroller_layout"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<include layout="@layout/item_1" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<include layout="@layout/item_2" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<include layout="@layout/item_3" />
</LinearLayout>
</LinearLayout>
</com.se.myapp.MyScroller>
这是项目在 xml 中的外观
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" "/>
</LinearLayout>
然后我在代码中像下面那样实现它。我重写了 onLayout 以更改项目所在布局的宽度,以反映手机屏幕的大小。
public class MyScroller extends HorizontalScrollView
{
...
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)
{
super.onLayout(changed, left, top, right, bottom);
LinearLayout layout = (LinearLayout) findViewById(R.id.scroller_layout);
mNoOfItems = layout.getChildCount();
int itemLayoutWidth = getMeasuredWidth();
for(int i = 0; i < mNoOfItems; i++)
{
View child = (View)layout.getChildAt(i);
ViewGroup.LayoutParams newLayout = new LinearLayout.LayoutParams(itemLayoutWidth , LinearLayout.LayoutParams.FILL_PARENT);
child.setLayoutParams(newLayout);
}
}
...
}
xml 中包含的项目只是带有 textview 的 LinearLayouts(稍后会更复杂)。我面临的问题是,如果我突然更改 onLayout 中 LinearLayouts 的布局,则当 textviews 中的文本更改时,项目将不会重新布局。因此,例如,如果我在第 1 项中有类似“test”的文本,并在应用程序运行时将该文本动态更改为“test123”,则不会显示“123”,因为 textview 的布局没有更新。奇怪的是,如果我不在 onLayout 中更改 LinearLayout 的布局,而是在 xml 中将其硬编码为 540px,则 textview 将在文本更改时更新其布局。我什至注意到,如果我在 xml 中将其硬编码为 540px,然后只需在代码中获取 layoutParams 并立即再次设置它而不更改以下任何内容,它也会停止工作。
child.setLayoutParams(child.getLayoutParams());
从 xml 设置 LinearLayout 的布局与从代码设置有什么不同吗?或者这种行为怎么会发生?
【问题讨论】:
标签: android android-layout android-linearlayout