
Androidアプリでユーザーからの文字入力を受け付けるには EditText を使います。
この記事ではEditTextの実装方法を、
実際に使ったサンプルコードを用いて説明していきます。
サンプルアプリ
「年齢を入力してボタンをクリックすると年齢区分が表示される」
アプリです!

こんな感じのアプリになります!
24歳はまだ青春期らしいです。笑
コードは最後に全て記載しておきます。

1.レイアウトxmlでEditText使い入力欄の準備
まずは入力欄のレイアウトだけ用意します。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/first_fragment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/armata"
android:text="年齢を入力してください"
android:textColor="#001D74"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.296" />
<EditText
android:id="@+id/input_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:fontFamily="@font/armata"
android:gravity="center"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.483"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.373" />
<Button
android:id="@+id/age_category_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#00BCD4"
android:text="年齢区分"
android:textColor="#FFFFFF"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/age_category_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/armata"
android:text=""
android:textColor="#001D74"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.655" />
</androidx.constraintlayout.widget.ConstraintLayout>
<EditText>のタグで囲まれた部分が入力欄となります。
android:gravity="center"
この行で入力された値を中央寄せにしています。
android:inputType="number"
この行で入力受付のバリデーションを数字のみに絞っています。
数字以外は入力できなくなるので、文字列が入力されることで起きるエラーを未然に防ぐことができます。
2.入力を受け付けるJava側のEditTextの準備
xmlに入力された値を受け取るJavaファイルを用意します。
public class FirstFragment extends Fragment {
private static final String TAG = "FirstFragment";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.first_fragment, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button ageCategoryButton = view.findViewById(R.id.age_category_button);
EditText editText = view.findViewById(R.id.input_age);
TextView ageCategoryResult = view.findViewById(R.id.age_category_result);
ageCategoryButton.setOnClickListener(clickView -> {
Log.d(TAG, "ageCategoryButton pressed!");
/* ボタンクリックのタイミングでキーボードを閉じる */
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(clickView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
if (TextUtils.isEmpty(editText.getText().toString())) {
/* 入力欄が空であれば何もしない */
Log.d(TAG, "Input age is empty.");
return;
}
int inputAge = Integer.parseInt(editText.getText().toString());
String ageCategory = selectAgeCategory(inputAge);
ageCategoryResult.setText(ageCategory);
});
}
/**
* Select age category from inputAge.
*
* @param age
* @return ageCategory
*/
private String selectAgeCategory(int age) {
Log.d(TAG, "Inputted age : " + age);
String ageCategory = "";
if (age < 0) {
ageCategory = "不正な年齢";
} else if (age < 15) {
/* 0 ~ 14歳 */
ageCategory = "幼少期";
} else if (age < 30) {
/* 15 ~ 29歳 */
ageCategory = "青春期";
} else if (age < 45) {
/* 30 ~ 44歳 */
ageCategory = "朱夏期";
} else if (age < 60) {
/* 45 ~ 59歳 */
ageCategory = "白秋期";
} else if (age < 75) {
/* 60 ~ 74歳 */
ageCategory = "玄冬期";
} else {
/* 75歳 ~ */
ageCategory = "高齢期";
}
Log.d(TAG, "Age category : " + ageCategory);
return ageCategory;
}
}
FragmentでUIを実装しています。
Fragmentの実装については「一番かんたんなFragmentの実装方法」を参考にしてください。
EditText editText = view.findViewById(R.id.input_age);
EditText型を使い、先ほど準備したxmlのEditTextに対応させておきます。
ageCategoryButton.setOnClickListener(clickView -> {
Log.d(TAG, "ageCategoryButton pressed!");
/* ボタンクリックのタイミングでキーボードを閉じる */
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(clickView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
if (TextUtils.isEmpty(editText.getText().toString())) {
/* 入力欄が空であれば何もしない */
Log.d(TAG, "Input age is empty.");
return;
}
int inputAge = Integer.parseInt(editText.getText().toString());
String ageCategory = selectAgeCategory(inputAge);
ageCategoryResult.setText(ageCategory);
});
ラムダ式のonClick() を使い、クリック後のイベントを実装しています。
コメントにもありますが、InputMethodManagerのhideSoftInputFromWindowメソッドを使い、
ボタンがクリックされたタイミングで、入力に使用したキーボードを閉じています。
Androidアプリでキーボードを閉じる際には必要となりますので覚えておくと吉です。
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
Fragmentから直接Contextを呼ぶことはできないので、
getActivity().getSystemService() でアクティビティを挟んで取得しています。
※ActivityからだとそのままgetSystemService()が使えます。
TextUtils.isEmpty(editText.getText().toString())
ユーザーから入力された値を editText.getText().toString() でString型にして取得しています。
TextUtilsのisEmptyメソッドを使って、入力された値が空ではないかを確認しています。
もし入力欄が空の場合は、return で返されその後の処理は行われません。
Androidアプリで、ユーザーに入力された値が空かをチェックする際には、参考にしてみてください。
int inputAge = Integer.parseInt(editText.getText().toString());
入力された値をint型に変換するために、一旦toString()でString型にしてからparseInt()で変換しています。
これでユーザーが入力した値をint型で取得できました!
あとは、selectAgeCategory()という自作メソッドを使って、年齢に合わせたString型の年齢区分を取得し、
setText()で反映させているだけです。
幼少期=0~14
青春期=15~29
朱夏期=30~44
白秋期=45~59
玄冬期=60~74
高齢期=75以上 っていうらしいです。青春期以降もかっこいいですね。

3.EditTextを使用した入力受付アプリのサンプルコード全容
コードを全て記載します。
activity_main.xml
first_fragment.xml
MainActivity.java
FirstFragment.java
からできており、MainActivityはFragmentを生成しているだけなので、
実際のコードの中核はFirstFragment.javaとfirst_fragment.xmlに集約されています。
ご精読ありがとうございました!!
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="@+id/fragment_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal">
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
first_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="@+id/first_fragment_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/armata"
android:text="年齢を入力してください"
android:textColor="#001D74"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.296" />
<EditText
android:id="@+id/input_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:fontFamily="@font/armata"
android:gravity="center"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.483"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.373" />
<Button
android:id="@+id/age_category_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#00BCD4"
android:text="年齢区分"
android:textColor="#FFFFFF"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/age_category_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/armata"
android:text=""
android:textColor="#001D74"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.655" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirstFragment firstFragment = new FirstFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, firstFragment);
transaction.commit();
}
}
FirstFragment.java
public class FirstFragment extends Fragment {
private static final String TAG = "FirstFragment";
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.first_fragment, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button ageCategoryButton = view.findViewById(R.id.age_category_button);
EditText editText = view.findViewById(R.id.input_age);
TextView ageCategoryResult = view.findViewById(R.id.age_category_result);
ageCategoryButton.setOnClickListener(clickView -> {
Log.d(TAG, "ageCategoryButton pressed!");
/* ボタンクリックのタイミングでキーボードを閉じる */
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(clickView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
if (TextUtils.isEmpty(editText.getText().toString())) {
/* 入力欄が空であれば何もしない */
Log.d(TAG, "Input age is empty.");
return;
}
int inputAge = Integer.parseInt(editText.getText().toString());
String ageCategory = selectAgeCategory(inputAge);
ageCategoryResult.setText(ageCategory);
});
}
/**
* Select age category from inputAge.
*
* @param age
* @return ageCategory
*/
private String selectAgeCategory(int age) {
Log.d(TAG, "Inputted age : " + age);
String ageCategory = "";
if (age < 0) {
ageCategory = "不正な年齢";
} else if (age < 15) {
/* 0 ~ 14歳 */
ageCategory = "幼少期";
} else if (age < 30) {
/* 15 ~ 29歳 */
ageCategory = "青春期";
} else if (age < 45) {
/* 30 ~ 44歳 */
ageCategory = "朱夏期";
} else if (age < 60) {
/* 45 ~ 59歳 */
ageCategory = "白秋期";
} else if (age < 75) {
/* 60 ~ 74歳 */
ageCategory = "玄冬期";
} else {
/* 75歳 ~ */
ageCategory = "高齢期";
}
Log.d(TAG, "Age category : " + ageCategory);
return ageCategory;
}
}
ピンバック: 【Kotlin】関数 / if文 / when文 の書き方 | Memento Mori Blog