ネイティブに Android でビューを動的に作成する方法
Androidにおける動的なViewの作成方法:
- 動的表示.xml
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dynamic_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dynamic TextView" />
- インフレータ
LayoutInflater inflater = LayoutInflater.from(context);
View dynamicView = inflater.inflate(R.layout.dynamic_view, null);
- 動的に作成したViewを親コンテナに追加します。例えば、動的に作成したTextViewをLinearLayoutに追加します。
LinearLayout linearLayout = findViewById(R.id.linear_layout);
linearLayout.addView(dynamicView);
この時点で、動的に生成されたTextView がLinearLayout 内に表示されるようになります。
ネイティブアプリで動的に生成したViewは、属性やリスナーなどを必要に応じて個別に設定する必要があります。