設置新的LayoutParams時,LinearLayout的子節點停止工作我在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中有「測試」這樣的文本,並且在應用程序運行時將該文本動態更改爲「test123」,則不會顯示「123」,因爲textview的佈局未更新。奇怪的是,如果我不更改onLayout中LinearLayout的佈局,但將其硬編碼爲xml中的540px,則textview將在文本更改時更新其佈局。我甚至注意到,如果我在xml中將它硬編碼爲540px,然後在代碼中獲得layoutParams並立即再次設置它,而不會像下面那樣改變任何東西,它也將停止工作。
child.setLayoutParams(child.getLayoutParams());
是否有與XML比代碼設置的LinearLayout佈局有什麼區別?或者這種行爲如何發生?