テーマに設定されている attribute は ? を使って参照することができます。
例えば、
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:background="?android:attr/selectableItemBackground"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="?android:attr/selectableItemBackground"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
とすることで、実際の画像リソースIDではなく、テーマの属性値を指定して、その属性値に設定されているリソースを利用することができます。
- <style name="Theme">
- <item name="selectableItemBackground">@android:drawable/item_background</item>
- ...
- </style>
<style name="Theme">
<item name="selectableItemBackground">@android:drawable/item_background</item>
...
</style>
このように XML から参照するのは簡単なのですが、コードからアクセスする方法はほとんど書かれていません。
具体的には、Theme クラスの
resolveAttribute() メソッドを使います。
- TypedValue outValue = new TypedValue();
- context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
- setBackgroundResource(outValue.resourceId);
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);
setBackgroundResource(outValue.resourceId);
インタラクションさせるカスタム View を作ったときに、コードから View を生成した場合でも、リストの行のようにタップしたときにデフォルトの色変化をさせたい場合に便利です。
0 件のコメント:
コメントを投稿