[簡単Androidアプリ] 背景にグラデーションを与える方法






背景にグラデーションを与えるには、eclipseの「パッケージ・エクスプローラー」内の「res」->「drawable」フォルダ内に新しく「xml」ファイルを作成し、そこにグラデーションを与える記述をします。では早速見て行きましょう。

まず、新しく「xml」ファイルを作成します。
drawable」フォルダを右クリックし「新規」、「Android XML ファイル」を選択

  • リソース・タイプを「Drawable
  • ファイル名を適当に入力、ここでは「gradientbackground」とする。
  • ルート要素を「shape」にし完了。



作成したXMLファイルに以下を記述。


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
    android:startColor="#339933"
    android:endColor="#99CC33"
    android:angle="270"/>
<corners android:radius="10dp"/>
</shape>

 グラデーションは<gradient>タグ内で設定しています。android:startColor=""にグラデーションのスタートの色を16進数カラーコードで指定し、android:endColor=""にグラデーションの終わりの色を16進数カラーコードで指定します。android:angle=""ではグラデーションがどの方角に向かうかかを角度で指定します。デフォルトでは0度となり、右から左へとグラデーションします。

 次に、layoutのxml内で先ほど作成したgradientbackground.xmlを背景として設定します。背景の設定は3行目のandroid:background="@drawable/作成したファイル名"で行います。以下activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@drawable/gradientbackground"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>








0 コメント: