システム開発ブログ

ボタンのデザインをxmlで定義する

千葉

千葉 (2012年1月31日 12:00)
システム開発事業部

システム開発事業部の千葉です。

Androidアプリを作るにあたり、ボタンの見た目を変えたいといった場合に、
よく使うのが背景用の画像を用意する方法ですが、
画面サイズの異なる端末をサポートしようとした場合、
どの端末の解像度に合わせるか、といった問題が出てきます。

そこで、今回はグラデーションを使用し、
ボタンのスタイルを定義する方法をご紹介します。
コードはこちらです。

■style1.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:shape="rectangle">
<gradient
android:angle="270"
android:startColor="#999999"
android:centerColor="#DDDDDD"
android:endColor="#222222"
android:type="linear" />
<corners
android:radius="5dp" />
<stroke
android:width="3dp"
android:color="#000000"/>
</shape>
</item>
</selector>

■style2.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:shape="rectangle">
<gradient
android:angle="270"
android:startColor="#EEEEEE"
android:endColor="#555555"
android:type="linear" />
<corners
android:radius="5dp" />
<stroke
android:width="3dp"
android:color="#000000"/>
</shape>
</item>
</selector>

■main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<Button
android:id="@+id/button1"
android:layout_width="150dp"
android:layout_height="50dp"
android:text="Button1" />

<Button
android:id="@+id/button2"
android:layout_width="150dp"
android:layout_height="50dp"
android:background="@drawable/style1"
android:text="Button2" />

<Button
android:id="@+id/button3"
android:layout_width="150dp"
android:layout_height="50dp"
android:background="@drawable/style2"
android:text="Button3" />

</LinearLayout>

実行した結果がこちらになります。

Screenshot_button.png

一番上が標準のボタン、二番目、三番目が今回作成したボタンです。

この方法であれば画面の解像度に依存することもありませんし、
さほど手間をかけずに見た目を変更できるので、
一つの方法として覚えておいて損はないと思います。
システムのトラブル解決を承ります。すぐにシステムリフォームを体験できますシステム診断・システムリフォームのお申し込みはこちらから。

システム開発ブログ

Twitterでilovex_officialをフォローしてください

最近の記事

カテゴリー

部署

月別アーカイブ

以前の部署別ブログ

ページのトップ