コードでボタンのStateによって色を変えるようにする
前回の続き的なノリで、コードでボタンのStateによって色を変えるように指定するコードを書いてみます。
API21以上の場合
API21以上の場合は、以下のように記述できます。
Button button = (Button) findViewById(R.id.button_bg_code); // 角丸の設定 int roundRadius = getResources().getDimensionPixelSize(R.dimen.button_round_radius); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setCornerRadius(roundRadius); int[][] states = new int[][] { new int[] {-android.R.attr.state_pressed}, // not pressed new int[] { android.R.attr.state_pressed} // pressed }; int [] colors = new int[] { Color.RED, Color.GREEN }; // API21以上対応 gradientDrawable.setColor(new ColorStateList(states, colors)); if (BuildConfig.VERSION_CODE >= 16) { button.setBackground(gradientDrawable); } else { button.setBackgroundDrawable(gradientDrawable); }
API20以下も対応する場合
これで先ほどと同じ振る舞いを確保しようとした場合は下記のようになります。
Button button = (Button) findViewById(R.id.button_bg_code); // 角丸の設定 int roundRadius = getResources().getDimensionPixelSize(R.dimen.button_round_radius); GradientDrawable gradientDrawableNotPressed = new GradientDrawable(); gradientDrawableNotPressed.setCornerRadius(roundRadius); gradientDrawableNotPressed.setColor(Color.RED); GradientDrawable gradientDrawablePressed = new GradientDrawable(); gradientDrawablePressed.setCornerRadius(roundRadius); gradientDrawablePressed.setColor(Color.GREEN); StateListDrawable stateListDrawable = new StateListDrawable(); stateListDrawable.addState(new int[] {-android.R.attr.state_pressed}, gradientDrawableNotPressed); // not pressed stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, gradientDrawablePressed); // pressed if (BuildConfig.VERSION_CODE >= 16) { button.setBackground(stateListDrawable); } else { button.setBackgroundDrawable(stateListDrawable); }
現場からは以上です。