Androidアプリ:ボタンの仕様を1つのxmlファイルにまとめる
Android Studioで、ボタンなどの色や形の指定をする際、1つのxmlファイルで、ボタンを押したときと押していないときの状態を指定する方法です。
xmlファイルの指定
Android Studioの左のツリーから、「res\drawable」の上で右クリック→「New」→「Drawable resource file」を指定します。
「File name:」に「button.xml」と入力して「OK」をクリックします。
「button.xml」に以下のように入力します。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape android:shape="rectangle">
<corners
android:radius="5dip"/>
<solid
android:color="#cccccc"/>
<padding
android:top="5dip"
android:bottom="5dip"
/>
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="rectangle">
<corners
android:radius="5dip"/>
<solid
android:color="#aaaaaa"/>
<padding
android:top="5dip"
android:bottom="5dip"
/>
</shape>
</item>
</selector>
<item android:state_pressed=”false”>は、ボタンが押されていない状態、
<item android:state_pressed=”true”>は、ボタンが押された状態を指します。
それぞれのitemタグ内にボタンの状態を記していきます。
<shape android:shape>
shapeには4種類指定できます。
rectangle |
四角形 |
oval |
楕円 |
line |
直線 |
ring |
円形 |
ringの場合に限り、以下の属性を設定できます。
android:innerRadius |
内側の円(中央の穴)の半径をdpで指定 |
android:innerRadiusRatio |
内側の円半径をリングの幅の比で指定。
デフォルトは9。
浮動小数で指定。 |
android:thicknes |
リングの厚みをdpで指定。 |
android:thicknessRatio |
リンクの厚みをリング幅の比で指定。
デフォルトは3。
浮動小数で指定。 |
android:useLevel |
LevelListDrawableとして使う場合はtrue |
LevelListDrawableとは、整数値であるLevelと画像を紐づけて、複数の画像を切り替えられるようにするものです。
<corners />
4隅の角丸の半径を数値で指定します。
<shape>~</shape>内に記載します。
android:radius |
4隅をまとめて指定 |
android:topLeftRadius |
左上 |
android:topRightRadius |
右上 |
android:bottomLeftRadius |
左下 |
android:bottomRightRadius |
右下 |
<gradient />
ボタンの背景色にグラデーションをかけます。
<shape>~</shape>内に記載します。
android:angle |
グラデーションの方向を0~360で指定。
0は左から右、
90は下から上、
180は右から左、
270は上から下。 |
android:centerX |
横軸の中心の位置を0~1.0で指定。 |
android:centerY |
縦軸の中心の位置を0~1.0で指定。 |
android:centerColor |
開始の色と終わりの色の中間色 |
android:endColor |
グラデーションの終わりの色 |
android:gradientRadius |
android:type=”radial”のときのみ指定可能。
グラデーションの半径をdpで指定。 |
android:startColor |
グラデーションの開始の色 |
android:type |
linearは、直線のグラデーション
radialは、放射状のグラデーション
sweepは、円形のグラデーション |
android:useLevel |
trueは、LevelListDrawableとして使う場合に指定。
falaseは使わない場合に指定。 |
<padding />
内部の余白の指定。
<shape>~</shape>内に記載します。
android:left |
左端からの余白をdpで指定 |
android:top |
上端からの余白をdpで指定 |
android:right |
右端からの余白をdpで指定 |
android:bottom |
下端からの余白をdpで指定 |
<size />
図形のサイズを指定します。
<shape>~</shape>内に記載します。
android:width |
図形の幅をdpで指定 |
android:height |
図形の高さをdpで指定 |
<solid />
背景色を単一で指定します。
<shape>~</shape>内に記載します。
android:color |
@color/色名
#cccccc |
「res\value\color.xml」に設定した色名(カラーリソース)を指定するか、「#cccccc」のように16進値を指定する、という方法があります。
<stroke />
枠線の太さや色を指定します。
<shape>~</shape>内に記載します。
android:width |
枠線の太さをdpで指定 |
android:color |
枠線の色を指定(xmlファイルもしくは16進値) |
android:dashWidth |
破線の線の長さをdpで指定 |
android:dashGap |
破線の間隔をdpで指定 |
dpで指定するものは、別途xmlファイルでディメンションリソースを設定しておけば、名前で指定することもできます。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="stroke_width">5dp</dimen>
<dimen name="font_size">24sp</dimen>
</resources>
関連記事