AndroidのTextInputLayoutが表示できなかった時の対応
Activityを持たないViewだけの生成で com.google.android.material.textfield.TextInputLayout を使おうと思った時に以下のエラーが発生した。
Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).
エラーの通りでテーマにTheme.AppCompatを指定しないといけないということだったけど Activityがない場合には、RootのViewGroupに設定を追加すればいいみたいだった。
<?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:theme="@style/Theme.AppCompat.DayNight.NoActionBar" <--------- 追加 android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.textfield.TextInputLayout android:id="@+id/textField" android:layout_width="match_parent"
設定したら問題なく表示された。
memo: ActivityやApplicationの追加はこちらのStackOverflowで確認できる。