【Android】ボタン操作でビュー(View)を動的に追加・削除する方法
このチュートリアルでは、Androidアプリの実行時にビュー(入力フィールド)を動的に追加・削除する方法を、サンプルコードとともに段階的に解説します。「連絡先の電話番号をいくつでも登録できるフォーム」のように、ユーザー操作に応じて入力欄を自由に増減させたい場合に非常に役立つテクニックです。
ステップ1:Android Studioで新規プロジェクトを作成する
Android Studioを起動し、メニューから「File」→「New Project」を選択して、必要な項目を入力して新しいプロジェクトを作成します。
ステップ2:res/layout/activity_main.xml にコードを追加する
まずはメイン画面のレイアウトです。親となるLinearLayoutの中に、初期表示用の入力行(電話番号入力用EditText+種類選択Spinner+削除ボタン)と、行を追加するための「Add Field」ボタンを縦方向に並べています。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
xmlns:app="https://schemas.android.com/apk/res-auto"
android:id="@+id/parent_linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:layout_margin="5dp"
android:orientation="vertical">
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<EditText
android:id="@+id/number_edit_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:inputType="phone"/>
<Spinner
android:id="@+id/type_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:entries="@array/types"
android:gravity="right"/>
<Button
android:id="@+id/delete_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="@android:drawable/ic_delete"
android:onClick="onDelete"/>
</LinearLayout>
<Button
android:id="@+id/add_field_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#555"
android:layout_gravity="center"
android:onClick="onAddField"
android:textColor="#FFF"
android:text="Add Field"
android:paddingLeft="5dp"/>
</LinearLayout>
ステップ3:res/layout/field.xml を作成する
次に、動的に挿入される「行」のテンプレートとなるレイアウトファイル res/layout/field.xml を新規作成し、以下のコードを記述します。中身は初期表示の入力行と同じ構成(EditText+Spinner+削除ボタン)になっています。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<EditText
android:id="@+id/number_edit_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:inputType="phone"/>
<Spinner
android:id="@+id/type_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:entries="@array/types"
android:gravity="right"/>
<Button
android:id="@+id/delete_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="@android:drawable/ic_delete"
android:onClick="onDelete"/>
</LinearLayout>
ステップ4:res/values/strings.xml にスピナーの選択肢を定義する
Spinnerに表示する選択肢(Mobile/Office/Home)を文字列配列として定義します。
<resources>
<string name="app_name">Sample</string>
<string-array name="types">
<item>Mobile</item>
<item>Office</item>
<item>Home</item>
</string-array>
</resources>
ステップ5:res/values/styles.xml を編集する
アプリの基本テーマを設定します。ここではアクションバーの高さも調整しています。
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="actionBarSize">36dip</item>
</style>
</resources>
ステップ6:src/MainActivity.java を実装する
ここが本題の核心部分です。追加ボタンのクリックイベントでLayoutInflaterを使ってfield.xmlを読み込み親レイアウトに挿入し、削除ボタンのクリックイベントでは該当する行をまるごと取り外します。
package com.example.sample;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private LinearLayout parentLinearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parentLinearLayout=(LinearLayout) findViewById(R.id.parent_linear_layout);
}
public void onAddField(View v) {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView=inflater.inflate(R.layout.field, null);
// Add the new row before the add field button.
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
}
コードのポイント:
- onAddField():LayoutInflaterでfield.xmlをインフレート(オブジェクト化)し、addView()の第2引数に「子ビュー数 − 1」を渡すことで、常に「Add Field」ボタンの直前に新しい行を挿入しています。
- onDelete():クリックされた削除ボタンのgetParent()でその親(=入力行全体のLinearLayout)を取得し、removeView()で一括削除します。これにより、どの行のボタンが押されても正しい行だけを消せます。
なお、本記事のコードは旧サポートライブラリ(android.support.v7)を使用していますが、最近のプロジェクトではAndroidX(androidx.appcompat.app.AppCompatActivity)への置き換えが推奨されています。パッケージ名を変更するだけで同様に動作します。
ステップ7:manifests/AndroidManifest.xml を確認する
最後にマニフェストファイルです。特別なパーミッションは不要で、MainActivityをランチャーアクティビティとして宣言しておきます。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
アプリを実行してみよう
それでは実際にアプリを起動してみましょう。Android端末をパソコンにUSB接続した状態で、Android Studio上の任意のアクティビティファイルを開き、ツールバーのRun(▶)アイコンをクリックします。デバイスの選択ダイアログで自分のスマホを選択すると、以下のような初期画面が表示されます。

「Add Field」ボタンをタップすると入力行がどんどん追加され、各行右側のゴミ箱アイコンをタップすればその行だけを削除できます。Spinnerでは電話番号の種類(Mobile/Office/Home)を選択可能です。

このように、LayoutInflaterとaddView()/removeView()を組み合わせるだけで、XMLを書き換えることなく実行時にUIを柔軟に構築できます。アンケートフォームや連絡先登録画面など、項目数が可変になるUIを作りたい際にぜひ活用してください。
-
AndroidスマホでGoogleアカウントを追加・削除・切り替える方法
新しいAndroid端末をセットアップする際、多くの人は初期設定の中でメインのGoogleアカウントを追加します。しかし、使い始めてから「同じ端末で別のアカウントにもアクセスしたい」と思うことがありますよね。 現在、個人用のメールアドレスに加えて、仕事用のメールを持っているユーザーは非常に多くいます。幸いなことに、Googleは1台の端末で複数のアカウントを簡単に切り替えられる仕組みを用意しています。 この記事では、Androidスマートフォンで複数のGoogleアカウントを追加・管理する方法を詳しく解説します。 スマホにサブのGoogleアカウントを追加する方法 Googleアカウントを端
-
iPhoneのグループメッセージにメンバーを追加・削除する方法を徹底解説
iPhoneはApple社が最も力を入れている製品の一つで、先進的なOSであるiOSならではの多彩な機能を備えています。その中でも特に便利なのがグループメッセージ(グループテキスト)機能です。この機能を使えば、複数人と同じグループ内で同時にやり取りできます。本記事では、iPhoneのグループメッセージにメンバーを追加する方法と、メンバーを削除する方法を詳しく解説します。 iPhoneでグループメッセージのメンバーを追加・削除するには? iPhoneではグループへのメンバー追加・削除が可能ですが、いくつか条件があります。 全員がiOSデバイスを使用していること(Androidユーザーが含まれ