LoginSignup
4
3

More than 5 years have passed since last update.

selectableItemBackground(RippleEffect)を動的に設定する

Posted at

はじめに

マテリアルデザインの特徴の一つにRippleEffectがありますが、xmlファイルに以下のように記述すれば簡単に実装することができます。

<TextView
    ...
    android:background="?attr/selectableItemBackground"
    ... />

条件の有無でこれを変えたい場合は、java側からセットする必要があります。

attrの呼び出し

attrをjavaから参照するには以下のようなコードを書きます。

TypedArray typedArray = context.obtainStyledAttributes(new int[]{R.attr.selectableItemBackground});
view.setBackgroundResource(typedArray.getResourceId(0, 0));
typedArray.recycle();

以下でもOKです。

TypedArray typedArray = context.obtainStyledAttributes(new int[]{R.attr.selectableItemBackground});
view.setBackground(typedArray.getDrawable(0));
typedArray.recycle();

引数の0はindexで、obtainStyledAttributesに渡しているint配列のindexを指定します。

paddingが消える

Android 6.1で検証したら正しく表示されましたが、Android 4.1.1では表示が崩れてしまいました。
原因は、selectableItemBackgroundが9-patchを含んでいて、9-patchを含んだものをbackgroundに指定するとpaddingが消えることがあるみたいです。
参考:http://stackoverflow.com/questions/10095196/whered-padding-go-when-setting-background-drawable
以下のようなコードを書くことで回避できます。

int l = view.getPaddingLeft();
int t = view.getPaddingTop();
int r = view.getPaddingRight();
int b = view.getPaddingBottom();

// 上述の処理

view.setPadding(l, t, r, b);
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3