LayoutInflaterクラスからレイアウトリソースをViewクラスに変換して、それをaddView()します。
例ではxmlファイルで定義した子レイアウトをメインレイアウトに追加する形で3つ縦に並べています。並べつつレイアウト上に配置されたTextViewのテキストを書き換えています。子レイアウト内のidの使い方も示しています。
public class SampleAppActivity extends Activity {
private final static String TAB = "SampleAppActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
for (int i = 0; i < 3; ++i) {
View view = getLayoutInflater().inflate(R.layout.sub, null);
layout.addView(view);
TextView text = (TextView) view.findViewById(R.id.text);
text.setText("I'm android No." + i);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/myname" />
</LinearLayout>
参考:Android Developers:LayoutInflater

No comments:
Post a Comment