LoginSignup
26
26

More than 5 years have passed since last update.

よくある感じのボタンをなるべく手抜きで作りたい

Last updated at Posted at 2014-04-13

開発してるとこんな感じのボタンを作りたくなる時がある。

a.png

デフォルトのボタンでは味気ないのでbackgroundを変えて手軽にフラットボタンっぽくしたい…という時。
実現するのには9patchを使ったり色々やり方はあるけど、エンジニア的にはxmlでselectorを書いたり、フラットな感じのボタンを作ってみたみたいにlayer-listを重ねて作るのが一番多い気がする。

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/label_button"
    android:background="@drawable/flat_button_background"/>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <solid android:color="@color/color_default" />
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape>
            <solid android:color="@color/pressed_color" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape>
            <solid android:color="@color/focused_color" />
        </shape>
    </item>
</selector>

一つ欠点があってとにかく面倒くさい。selectorの書き方とかすぐ忘れるので、いちいちググったり過去のソースコードを見に行ってコピペしたりするのはストレスだと思う。

という事でEasyButtonというCustom Viewを作って対応してみた。

  • color_default
  • color_pressed
  • color_focused

3つのattributeにcolorを設定すれば良い。
設定しなかった場合はAndroidデフォルトのStyleが適用される。

<easybutton.EasyButton
    android:id="@+id/button"
    android:text="@string/button_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:color_default="@color/color_default"
    tools:color_pressed="@color/color_pressed"
    tools:color_focused="@color/color_focused" />

Maven Centralにaarを上げておいたのでお好みの方はどうぞ。

  dependencies {
    compile 'com.github.hotchemi:easy-button:{latest.version}'
  }
26
26
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
26
26