サポートライブラリAndroid Design Support Libraryのandroid.support.design.widget.TextInputEditTextは同じパッケージ内にあるTextInputLayoutと組み合わせて、テキスト入力機能を提供するViewです。
マテリアルデザインのText Fieldsによく従っているので、アプリ外観をマテリアルデザイン風にしたい時に使います。
ヒントをアニメーションしたり…floating labelsというらしい…指定文字以上入力すると背景を変えてエラー表示してくれたりと、お手軽にちょっとかっこいいデザインぽくなります。
逆に言うと見た目に関して勝手によきに計らってしまうのでうぅーとなってしまう時があります(。・_・。)
で、タイトルの「TextInputEditTextに透過色の背景を割り当てる時はView#setBackground(Drawable background)で」、です。
普通のViewであればView#setBackgroundColorで透過色(アルファ値付きの色)を指定するとViewが透けて見えるのですが、TextInputEditTextは#setBackgroundColorで透過色を指定しても思ったようには透過してくれません(´・ω・`) 一緒に配置している他のViewとは違った色になってしまいます。
ソースコードを追っかけていくと、TextInputEditTextはTintableBackgroundView(android.support.v4.view.TintableBackgroundView)というインターフェースを実装していて自動的にtint(薄い色を付ける)が付くようになっています。思った通りに透過しない原因はデフォルトで掛かるこのtintにあります。
TextInputEditTextでのtintの処理は、AppCompatBackgroundHelper(android.support.v7.widget)というパッケージローカルのクラスで行っているようです。その中に、
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
void onSetBackgroundResource(int resId) { mBackgroundResId = resId; // Update the default background tint setInternalBackgroundTint(mDrawableManager != null ? mDrawableManager.getTintList(mView.getContext(), resId) : null); applySupportBackgroundTint(); } void onSetBackgroundDrawable(Drawable background) { mBackgroundResId = -1; // We don't know that this drawable is, so we need to clear the default background tint setInternalBackgroundTint(null); applySupportBackgroundTint(); } void setSupportBackgroundTintList(ColorStateList tint) { if (mBackgroundTint == null) { mBackgroundTint = new TintInfo(); } mBackgroundTint.mTintList = tint; mBackgroundTint.mHasTintList = true; applySupportBackgroundTint(); } |
という部分があります。つまり即値指定、リソースIDでカラーまたはDrawableを指定、またはColorStateListで背景を設定すると自動でデフォルトのtintがかかるようになっています。でもDrawableを指定した時だけ「We don’t know that this drawable is, so we need to clear the default background tint」と書いてある通りデフォルトのtintが無効になってくれます。
本来はTintableBackgroundViewで定義してあるメソッド
1 2 3 4 5 |
ColorStateList getSupportBackgroundTintList() PorterDuff.Mode getSupportBackgroundTintMode() void setSupportBackgroundTintList(ColorStateList tint) void setSupportBackgroundTintMode(PorterDuff.Mode tintMode) void setSupportBackgroundTintList(ColorStateList) |
を使ってゴニョゴニョするのが筋なんでしょうが、別にtintも要らんしエラー時に背景変えんでもええねんと言う時は、View#setBackgroundColorの代わりにView#setBackgroundで背景としてDrawableを割り当てるとtintがかからずに好きな背景に変更することが出来ます。
まぁ、Android Design Support Libraryのクラスは割と結構、中の実装方法や挙動が変わったりするのでいつまで有効かはわかりませんが、そういうことを言い出すとそもそも公式の方法だっていつまで使えるか、思った通りに動くかどうかはわからないわけで(汗)
テキスト入力部分がむやりやたらと透過していると下地と文字色によっては文字が見えにくくなったりしますので程々に、とりあえず自己責任でお願いします^^;