Skip to content

Instantly share code, notes, and snippets.

@chuross
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuross/eb82ad9a9e5e6c51308b to your computer and use it in GitHub Desktop.
Save chuross/eb82ad9a9e5e6c51308b to your computer and use it in GitHub Desktop.
```java
public static void setBackgroundColor(View view, int color) {
if(view == null) {
return;
}
// 4.2以降は対応済みなのでそのまま処理する
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
view.setBackgroundColor(color);
return;
}
// そのまま呼ぶとColorDrawableが既にセットされてた時にDrawableのmutateが呼ばれないので手動で処理する
if(view.getBackground() instanceof ColorDrawable) {
((ColorDrawable) view.getBackground().mutate()).setColor(color);
view.computeOpaqueFlags();
} else {
view.setBackgroundDrawable(new ColorDrawable(color));
}
}
```
修正前だとColorDrawableの内部でColorStateを複製していないのでmutate呼んでももしかしたらだめかも
https://github.com/android/platform_frameworks_base/commit/5f49c3023a512efbef8bc9515d310c7a72be4af2#diff-b61568e8094d7de01579459b3a9fbd55R76
```java
public static void setBackgroundColor(View view, int color) {
if(view == null) {
return;
}
// 4.2以降は対応済みなのでそのまま処理する
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
view.setBackgroundColor(color);
return;
}
view.setBackgroundDrawable(new ColorDrawable(color));
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment