Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】ソフトウェアキーボード(仮想キーボード)の表示状態を確認する方法


はじめに

Androidアプリ開発では、特定のアクティビティ上でソフトウェアキーボード(仮想キーボード)が表示されているかどうかを判定したい場面があります。本記事では、ViewTreeObserverを活用してキーボードの表示状態を検出する方法を、実際のサンプルコードとともに詳しく解説します。

ステップ1:プロジェクトの作成

まずはAndroid Studioで新しいプロジェクトを作成しましょう。メニューから[File] → [New Project]を選択し、必要な項目を入力してプロジェクトを作成します。

ステップ2:レイアウトファイルの作成

res/layout/activity_main.xmlに以下のコードを追加します。画面にはEditTextとボタンを1つずつ配置しています。

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.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/editext"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content">
   </EditText>
   <Button
      android:id = "@+id/button"
      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" />
</android.support.constraint.ConstraintLayout>

ステップ3:MainActivity.javaの実装

src/MainActivity.javaに以下のコードを追加します。

import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
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.button);
      EditText editText=findViewById(R.id.editext);
      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.button:
         hideSoftkeybard(v);
         break;
      }
   }
   private void hideSoftkeybard(View v) {
      InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
      inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
   }
}

キーボード判定の仕組み

このコードでは、ViewTreeObserver.OnGlobalLayoutListenerを使用して、アクティビティのレイアウト変更を常時監視しています。判定の流れは以下の通りです。

まず、ルートビューの高さ(画面全体の高さ)を取得します。

int screenHeight = constraintLayout.getRootView().getHeight();

次に、getWindowVisibleDisplayFrame()で取得できる可視領域と画面全体の高さの差分から、キーボードの高さを算出します。

Rect r = new Rect();
constraintLayout.getWindowVisibleDisplayFrame(r);
int keypadHeight = screenHeight - r.bottom;

最後に、キーボードの高さが画面全体の高さの15%を超えているかどうかを比較して、表示状態を判定します。この閾値を設けることで、ナビゲーションバーなどによる誤検知を防いでいます。

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();
}

ステップ4:AndroidManifest.xmlの設定

AndroidManifest.xmlに以下のコードを追加します。

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
package = "com.example.andy.myapplication">
   <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"
         android:windowSoftInputMode = "stateAlwaysVisible">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

ここでは、activity要素にandroid:windowSoftInputMode="stateAlwaysVisible"を指定しています。この設定により、EditTextにフォーカスが当たると自動的にキーボードが表示されるようになります。

アプリの実行と動作確認

それでは、アプリケーションを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続しているものとします。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「実行」アイコンをクリックしてください。実行デバイスとして自分のモバイル端末を選択すると、端末にアプリの初期画面が表示されます。

【Android】ソフトウェアキーボード(仮想キーボード)の表示状態を確認する方法

キーボードが表示されている状態では、Toastで「Keyboard is showing」というメッセージが表示されます。

【Android】ソフトウェアキーボード(仮想キーボード)の表示状態を確認する方法

続いて、ボタンをタップしてキーボードを非表示にしてみましょう。「keyboard closed」というメッセージが表示されれば成功です。

補足:最新のAndroid開発での代替手段

本記事のコードはサポートライブラリ(android.support)時代の実装例です。現在のプロジェクトではAndroidXへの移行が推奨されており、API 30以降ではWindowInsetsCompatViewCompat.setOnApplyWindowInsetsListener()を利用することで、より確実にIME(キーボード)の表示状態を取得できます。新規開発の場合は、こうしたモダンな手法の採用も検討してみてください。

まとめ

キーボードの表示状態を判定するポイントは、ViewTreeObserver.OnGlobalLayoutListenerでレイアウト変更を監視し、画面全体の高さと可視領域の差分からキーボードの高さを求めることです。あとは15%という閾値と比較するだけで、シンプルかつ確実に判定できます。入力フォームを含むUIの改善などに、ぜひ活用してください。

  1. Androidスマホでキーボードのサイズを変更する方法|Gboard・Samsung Keyboardなど徹底解説

    近年、スマートフォンの大画面化が進み、多くのユーザーが大きな画面を好むようになりました。大画面はスタイリッシュな印象を与えるだけでなく、特に高齢の方にとっては視認性が大きく向上するというメリットもあります。しかし一方で、画面の大型化に伴い、「片手での文字入力がしづらくなった」という新たな悩みも生まれています。 幸い、この問題にはいくつかの解決策があります。本記事では、Androidスマートフォンでキーボードのサイズを変更するさまざまな方法をご紹介します。 キーボードのサイズ変更には複数のアプローチがあります。視認性と入力精度を高めるために拡大するのもよし、片手操作を快適にするために縮小するのも

  2. Androidでバッテリーの劣化状態を確認する方法|隠しコードとアプリ活用術

    スマートフォンからリモコンまで、私たちの身の回りの多くの機器はバッテリーで動作しています。バッテリーは今や現代生活に欠かせない存在です。特にモバイル端末に搭載されているリチウムイオンバッテリーは、長期間の使用により必ず劣化していきます。劣化の兆候としては、充電時間の長期化や不安定化、充電容量の低下、発熱、急激なバッテリー消耗、バッテリーの膨張などが挙げられます。バッテリーとデバイス本体を長持ちさせるためには、定期的にバッテリーの状態を確認し、適切なメンテナンスを行うことが重要です。この記事では、Androidでバッテリーの状態を確認する方法を詳しく解説します。 Androidでバッテリーの状