2

main.xmlLinearLayout )内にビュー要素があります:ScrollView

<ScrollView ...>

   <LinearLayout
       android:id="@+id/root"
       android:orientation="vertical"
    >
          <TextView .../>
          <EditText .../>
          ...
    </LinearLayout>

</ScrollView>

上記のように、root LinearLayout内には他の要素もあります。

LinearLayoutここで、プログラムで (動的に) ビューを(id="root")に追加したいと思います。

このルートにさらに子ビューを追加するために、次の方法を試しました

まず、別のレイアウト ファイルにある子ビューを作成しました。

child.xml

<LinearLayout
    android:id="@+id/child"
>
     <TextView id="mytxt"... />
     <ListView id="mylist".../>
</LinearLayout>

次に、上記の子ビューの 2 つのインスタンスをインフレートして取得し、内部の要素を初期化します。

/***inflate 1st child, initialize its elements***/
LinearLayout child_1 = (LinearLayout) inflater.inflate(R.layout.child, null);
TextView txt1 = (TextView)child_1.findViewById(R.id.mytxt);
txt1.setText("CAR");
ListView list1 = (ListView)child_1.findViewById(R.id.mylist);
// Code to initialize 'list1' (I did not paste code here)


/*** inflate 2nd child, initialize its elements ****/
LinearLayout child_2 = (LinearLayout) inflater.inflate(R.layout.child, null);
TextView txt2 = (TextView)child_2.findViewById(R.id.mytxt);
txt2.setText("PLANE");
ListView list2 = (ListView)child_2.findViewById(R.id.mylist);
// Code to initialize 'list2' (I did not paste code here)

最後に、それらをルート に追加しますLinearLayout

//get root
View contentView = inflater.inflate(R.layout.main, null);
LinearLayout root = (LinearLayout) contentView.findViewById(R.id.root);

//add child views
root.add(child_1);
root.add(child_2);

child_2デバイスでアプリを実行すると、「ルート」の下が表示されずにレイアウトしか表示されないchild_1のはなぜですか??

4

2 に答える 2

2

LinearLayoutのデフォルトの向きは水平で、垂直に設定します........

http://developer.android.com/reference/android/widget/LinearLayout.htmlから

見る

デフォルトの向きは水平です。

and you set text in txt1.setText("PLANE"); set in  txt2.setText("PLANE");

both text set in same textview.....

    txt1.setText("CAR");
    txt1.setText("PLANE"); 
于 2012-06-07T14:03:08.417 に答える
1

レイアウトはどのように作成しますか? を通してやりますsetContentView(int)か?次に、アクティビティでこれを実行して、そのインスタンスを取得する必要があります。

findViewById(R.id.root);
于 2012-06-07T14:05:25.307 に答える