2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Android】ボタンの色や形を動的に変更する

Last updated at Posted at 2021-03-04

xml上での設定ではなく、ボタンの角丸・輪郭・押下時のレイアウト変更を動的に設定する方法のメモ。

手順

xmlでボタン作成

activity_main.xml
<androidx.appcompat.widget.AppCompatButton
    android:id="@+id/button"/>

kotlin内でレイアウト定義

MainActivity.kt
val drawable = GradientDrawable()

//グラデーションにしたい時
//val drawable = GradientDrawable(GradientDrawable.Orientation.RIGHT_LEFT, intArrayOf(Color.parseColor("#77ccff"), Color.parseColor("#88ddff")))

//ボタンの色指定
drawable.color = ColorStateList.valueOf(Color.parseColor("#99eeff"))

//ボタン押下時・通常時で色を変更したい時
//drawable.color = ColorStateList(
//    arrayOf(intArrayOf(android.R.attr.state_pressed), intArrayOf()),
//    intArrayOf(Color.parseColor("#88ddff"), Color.parseColor("#99eeff"))
//)

//角丸
drawable.cornerRadius = 200f

//輪郭
drawable.setStroke(6, Color.parseColor("#77ccff"))

//上記で設定したdrawableをボタン背景に設定
binding.button.background = drawable
2
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?