从代码设置新的LayoutParams时,LinearLayout的子节点的重新布局停止工作

时间:2011-07-19 21:08:24

标签: android android-layout android-linearlayout

我在Android中有一个Horizo​​ntalScrollView,在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中包含的项目只是LinearLayouts,其中包含textview(稍后会更复杂)。我面临的问题是,如果我在onLayout中更改LinearLayouts的布局,那么当textview中的文本发生变化时,项目将不会重新布局。因此,如果我在第1项中有类似“test”的文本,并在应用程序运行时动态地将该文本更改为“test123”,则不会显示“123”,因为textview的布局未更新。奇怪的是,如果我不在onLayout中更改LinearLayout的布局,但是在xml中将其硬编码为540px,则textview将在文本更改时更新其布局。我甚至注意到,如果我在xml中将其硬编码为540px,然后只需在代码中获取layoutParams并立即再次设置它而不更改如下所示,它也将停止工作。

child.setLayoutParams(child.getLayoutParams());

从xml设置LinearLayout的布局与从代码设置是否有任何区别?或者这种行为如何发生?

1 个答案:

答案 0 :(得分:0)

我发现了问题,我不得不打电话给super.onLayout(更改,左,上,右,下);在我调用了child.setLayoutParams(newLayout);之后,我重新编写了它,以便我从onSizeChanged改变layoutparams,这样做效果很好。

相关问题