2

プログラムでビューグループを別のビューグループに追加できるようにしたいと思います。両方とも、私のonCreateメソッドとともに、次のようにxmlで定義されています。

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/firstll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="first text" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="second text" />

secondlayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/secondll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="first text" />

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="second text" />

onCreate:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Context context = getBaseContext();

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.main, null);
    LinearLayout tv = (LinearLayout) inflater.inflate(R.layout.secondlayout, null);
    tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    ll.addView(tv);
    setContentView(ll);
}
4

1 に答える 1

2

コンテンツビューを設定する前に、ビューを見つけようとしていますfindViewById(R.layout.secondlayout)。また、secondlayoutビューのIDではなく、レイアウトファイルの名前とIDです。

やってみてください

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.main, null);
LinearLayout tv = (LinearLayout) inflater.inflate(R.layout.secondlayout, null);
tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(tv);
setContentView(ll);
于 2011-12-08T18:01:59.623 に答える