【Android】アクティビティでソフトキーボードの開閉リスナーを実装する方法
この記事では、Androidアプリのアクティビティ内でソフトキーボード(SoftKeyboard)の表示・非表示を検知するリスナーを実装する方法を、サンプルコードとともにわかりやすく解説します。
ソフトキーボードの開閉を検知するには、ViewTreeObserver.OnGlobalLayoutListener を利用して、画面の可視領域の変化を監視するのが一般的な手法です。
手順1:新規プロジェクトの作成
Android Studioを起動し、メニューから「File」→「New Project」を選択して、必要な項目を入力して新しいプロジェクトを作成します。
手順2:レイアウトファイル(res/layout/activity_main.xml)の編集
以下のコードを activity_main.xml に追加します。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id = "@+id/rootView"
tools:context=".MainActivity">
<EditText
android:id = "@+id/editText"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
tools:ignore="MissingConstraints">
</EditText>
<Button
android:id = "@+id/btnButton"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Click here to hide"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</androidx.constraintlayout.widget.ConstraintLayout>このレイアウトには、キーボードを表示させるための EditText と、キーボードを非表示にするための Button を配置しています。
手順3:MainActivity.java の実装
次に、src/MainActivity.java に以下のコードを追加します。
package com.app.sample;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.os.Bundle;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
ConstraintLayout constraintLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.btnButton);
EditText editText=findViewById(R.id.editText);
editText.requestFocus();
constraintLayout=findViewById(R.id.rootView);
constraintLayout.getViewTreeObserver().addOnGlobalLayoutListener(new
ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
constraintLayout.getWindowVisibleDisplayFrame(r);
int screenHeight = constraintLayout.getRootView().getHeight();
int keypadHeight = screenHeight - r.bottom;
if (keypadHeight > screenHeight * 0.15) {
Toast.makeText(MainActivity.this,"Keyboard is showing",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"keyboard closed",Toast.LENGTH_LONG).show();
}
}
});
button.setOnClickListener(this);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnButton:
hideSoftkeybard(v);
break;
}
}
private void hideSoftkeybard(View v) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}仕組みのポイント
getWindowVisibleDisplayFrame()で画面の可視領域を取得し、ルートビュー全体の高さとの差分からキーボードの高さを算出しています。- キーボードの高さが画面全体の15%を超えていれば「表示中」、それ以下なら「閉じている」と判定するシンプルなロジックです。
- ボタン押下時には
InputMethodManager.hideSoftInputFromWindow()を呼び出して、ソフトキーボードを明示的に非表示にしています。
手順4:AndroidManifest.xml の設定
最後に、Manifests/AndroidManifest.xml に以下のコードを追加します。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.app.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スマートフォンがPCに接続されているものとして説明します。
Android Studioからプロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックしてください。デバイス選択画面で接続したモバイル端末を選択すると、実機上でアプリが起動します。
アプリが起動すると、EditText にフォーカスが当たりソフトキーボードが自動的に表示され、「Keyboard is showing」というトーストが表示されます。ボタンをタップしてキーボードを閉じると、今度は「keyboard closed」というトーストが表示されることを確認できます。
-
Androidのアセットフォルダからファイルを読み込む方法【サンプルコード付きで解説】
このチュートリアルでは、Androidアプリでアセット(assets)フォルダ内のファイルを扱う方法を、実際に動作するサンプルコードとともに段階的に解説します。なお、アセットフォルダはAPKにパッケージ化される読み取り専用の領域であるため、実行時に新しいファイルを書き込むことはできません。そこで本記事では、アセットフォルダに配置したテキストファイルを読み込み、画面に表示するまでの一連の手順を紹介します。ステップ1:新規プロジェクトを作成するAndroid Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成
-
AndroidでHEIC画像を開く・JPGに変換する方法を徹底解説
iPhoneで撮影した写真は、iOS 11以降では従来のJPG形式ではなく、HEICファイルとして保存されるようになりました。しかし、この新しい形式には他のアプリやデバイスとの互換性が十分でないという課題があります。そのため、パソコンやAndroidスマートフォンでは開けないケースもあります。さらに、Androidの標準アプリの多くはまだこの形式に対応していません。本記事では、AndroidでHEICファイルを開く方法から、JPGへの変換方法まで、初心者にもわかりやすく解説します。HEICファイルとは?HEICとは、Appleが採用する最新の画像形式「HEIF(High Efficiency