2013年4月28日日曜日

Android サンプルコード徹底解説 - SkeletonApp (Part2)

次はソースコードを覗いて見ましょう。
まず最初は、画面定義XML (skeleton_activity.xml) です。
Package Explorer で SkeletonApp > res > layout と選択し、skeleton_activity.xml をダブルクリックします。
グラフィックモードになっている場合は、下部の skeleton_activity.xml タブをクリックしてXMLモードに切り替えます。すると、以下のような画面定義XMLが表示されると思います。
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!-- This file describes the layout of the main SkeletonApp activity
     user interface.
 -->

<!-- The top view is a layout manager that places its child views into
     a row, here set to be vertical (so the first is at the top) -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- First view is a text editor.  We want it to use all available
         horizontal space, and stretch to fill whatever vertical space
         is available to it.  Note the use of the "id" attribute, which
         allows us to find this object from the Java code. -->
    <EditText android:id="@+id/editor"
        android:layout_width="match_parent" android:layout_height="0dip"
        android:autoText="true"
        android:capitalize="sentences"
        android:layout_weight="1"
        android:freezesText="true" >
        <requestFocus />
    </EditText>

    <!-- Next view is another linear layout manager, now horizontal.  We
         give it a custom background; see colors.xml for the definition
         of drawable/semi_black-->
    <LinearLayout
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:background="@drawable/semi_black">

        <!-- On the left: the "back" button.  See styles.xml for the
             definition of style/ActionButton, which we use to hold
             common attributes that are used for both this and the
             clear button.  See strings.xml for the definition of
             string/back. -->
        <Button android:id="@+id/back" style="@style/ActionButton"
            android:text="@string/back" />

        <!-- In the middle: a custom image, -->
        <ImageView android:id="@+id/image"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:paddingLeft="4dip" android_paddingRight="4dip"
            android:src="@drawable/violet" />

        <!-- On the right: another button, this time with its text color
             changed to red.  Again, see colors.xml for the definition. -->
        <Button android:id="@+id/clear" style="@style/ActionButton"
            android:text="@string/clear" android:textColor="@color/red" />

    </LinearLayout>

</LinearLayout>

この画面定義XML により以下のような画面が作成されます。
どの定義がどの画面の部品になっているかの注釈を記入しています。


ソースコードの解説

そもそも XML って何?という人は、コラム「XMLとは」を参照してください。

1行目
 <?xml version="1.0" encoding="utf-8"?> はXML宣言といって、その文書がXMLで記述されていることを知らせるためのものです。XML宣言は必ず先頭に記述し、それ以前に空白文字や空行があってはいけません。

version="1.0" は XML のバージョンを記述します。

encoding="utf-8" は XML文書の文字コードを指定します。

2〜15行目
<!-- と --> に囲まれた緑の文字の部分はコメントです。
コメントには何を記入してもかまいませんが、通常はライセンスとかプログラムの説明など意味のある文字を記入します。プログラムはコンピュータが読みますが、コメントは人が読むので人が読んで分かるように記入します。

24〜26行目
この「LinearLayout」タグにより 赤枠の (1)LinearLayout が作成されます。
LinearLayout はGUI部品(コンポーネントともいう)を入れる箱のような役割をし、画面には何も表示されません。

xmlns:android="http://schemas.android.com/apk/res/android" とは名前空間の指定で最初のエレメント(ルートエレメントともいう)では必ず指定します。今のところは、こんなもんだ程度の理解でOKです。

android:layout_width="match_parent" android:layout_height="match_parent" は幅と高さをどれくらいにするかを指定します。どちらも match_parent と指定されています。親のサイズにマッチするようにするという意味です。ここでは親がないルートエレメントなので画面いっぱいのサイズになります。

android:orientation="vertical" は LinearLayout の子要素として中に入れるGUIコンポーネントを縦に配置するという意味です。

32〜39行目
この「EditText」タグにより 緑枠の (2)EditText が作成されます。
EditText は文字を入力するボックスです。

android:id="@+id/editor" は ID を指定します。editor と定義しています。プログラム内でこのGUIコンポーネントにアクセスするときに使います。プログラムからアクセスしない場合には付ける必要はありません。「@+id/」は、 R.java というリソースを管理するファイルに登録するという意味で、今のところは、必ず付けるものという理解でOKです。

android:layout_width="match_parent" android:layout_height="0dip" は幅と高さをどれくらいにするかを指定します。幅の match_parent は親のサイズにマッチするようにするという意味です。親は (1)LinearLayout なので、 (1)LinearLayout と同じ幅になります。高さの 0dip は高さを0にするという意味です。えー!、高さ0なのに何で表示されてるの?という疑問が出ますが、後述の
android:layout_weight="1" の箇所で説明します。
あと、単位の dip については、コラム「Android の画面単位について」を参照してください。

android:autoText="true" は、入力値のスペルミスの修正を自動で行います。

android:capitalize="sentences" は、各文の先頭文字を自動で大文字に変換します。

android:layout_weight="1" は、親コンポーネントの余った余白を分け合う比率を指定します。
以下の図を見てください。
一番外側の赤い枠で囲った部分が親コンポーネントです。
その中に、EditText(緑枠) と LinearLayout(黄色枠) があります。
下の黒い部分が余白です。この余白を子コンポーネントでどう分け合うかの比率を指定するのが layout_weight です。上図では、EditText にも LinearLayout にも layout_weight は指定していません。なので、余白は余白のままとなります。例えば、EditText の layout_weight=2 で、 LinearLayout の layout_weight=1 となっていた場合は、2対1の割合で、余白が分合われます。
skeleton_activity.xml では、EditText のみに layout_weight が指定されていて、他のコンポーネントは指定されていません。なので、余白は EditText が全てもらうことになります。これが layout_height="0dip" なのに高さが確保される理由です。

android:freezesText="true" は、アクティビティが破棄されてから再構築されるまでの間で、入力途中のテキストの内容を保持するかどうかを指定します。これを指定しておかないと画面の縦横切り替えを行うと入力内容が失われます。

38行目
この「requestFocus」タグは、指定されているコンポーネントに、カーソル(フォーカス)を当てます。

44〜49行目
この「LinearLayout」タグにより 黄色枠の (3)LinearLayout が作成されます。
24行目でも登場しましたが、再びの登場です。このように入れ子にすることができます。

android:layout_width="wrap_content" android:layout_height="wrap_content" は幅と高さをどれくらいにするかを指定します。今度は warp_content が指定されています。表示に必要なサイズにするという意味で、自動的に適切な幅と高さに調整してくれます。

android:layout_gravity="center_vertical" は、コンポーネントの配置を上下左右のどちらに寄せるかを指定します。center_vertical で垂直方向に対して中央に配置されます。layout_gravity は自身のコンポーネントのみが対象となり、中に含まれる子コンポーネントは対象外です。つまり、LinearLayout 自体が中央に配置され、中の子コンポーネントの配置には影響しません。

android:gravity="center_horizontal" は、コンポーネントの配置を上下左右のどちらに寄せるかを指定します。center_horizontal で水平方向に対して中央に配置されます。gravity は含まれる子コンポーネントの配置が対象となります。

layout_gravity と gravity とよく似たのが2つあってややこしいのですが、まとめると
layout_gravity : コンポーネント自身の配置を指定。
gravity : コンポーネントの中に含まれる子コンポーネントの配置を指定。

android:orientation="horizontal" は LinearLayout の子要素として中に入れるGUIコンポーネントを横に配置するという意味です。

android:background="@drawable/semi_black" は背景色を指定します。semi_black と指定されていますが、これは res/values/colors.xml の中で定義されています。@drawable は drawable として定義されているという意味です。ファイル名は何でもよくて、drawable タグで名前が semi_black として定義されている値が使われます。

colors.xml を見ますと #80000000 と定義されています。
この #80000000 は #AARRGGBB の形式で定義されており、最初の # は16進数という意味。
AA : アルファ値で透明度を指定。小さいほど透明で、大きいほど不透明になる。
RR : 赤の色。小さいほど薄く、大きいほど濃い赤になる。
GG : 緑の色。小さいほど薄く、大きいほど濃い緑になる。
BB : 青の色。小さいほど薄く、大きいほど濃い青になる。
それぞれ、0〜255の数値で指定します。(16進数だと00〜ffの数値)
この RGB (赤緑青)の組み合わせで 16,777,216色の色が表現できます。

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!-- This file contains resource definitions for solid colors.  In
     addition to plain color resources (retrieved via Resources.getColor()
     and friends), we are also using it to define drawables that are
     a solid color. -->

<resources>
    <!-- Retrieved via Resources.getColor() and friends. -->
    <color name="red">#f00</color>

    <!-- Retrieved via Resources.getDrawable() and friends. -->
    <drawable name="semi_black">#80000000</drawable>
</resources>

56〜57行目
この「Button」タグにより、Back ボタンが作成されます。

android:id="@+id/back" は ID を指定します。back と定義しています。プログラム内でこのGUIコンポーネントにアクセスするときに使います。プログラムからアクセスしない場合には付ける必要はありません。「@+id/」は、 R.java というリソースを管理するファイルに登録するという意味で、今のところは、必ず付けるものという理解でOKです。

style="@style/ActionButton" は、スタイルを設定します。ActionButton と指定されていますが、これは res/values/style.xml の中で定義されています。@style は style として定義されているという意味です。ファイル名は何でもよくて、style タグで名前が ActionButton として定義されている値が使われます。ActionButton では、
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textAppearance">@style/TextAppearance.ActionButton</item>
が定義されています。さらに、textAppearanceでは、@style/TextAppearance.ActionButton の値が参照されますので、
<item name="android:textStyle">italic</item>
と定義されています。
つまり、幅と高さが wrap_content (自動的に表示に必要な適切なサイズに調整される)、文字のスタイルがイタリックに、ということになります。

<resources>
    <style name="ActionButton">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textAppearance">@style/TextAppearance.ActionButton</item>
    </style>

    <style name="TextAppearance" parent="android:TextAppearance">
    </style>

    <style name="TextAppearance.ActionButton">
        <item name="android:textStyle">italic</item>
    </style>

</resources>

android:text="@string/back" はボタンの上に表示される文字を指定します。 back と定義されていますが、res/values/strings.xml の中で定義されています。@string は string タグとして定義されているという意味です。ファイル名は何でもよくて、string タグで名前が back として定義されている値 (=Back) が使われます。ここに直接 text="ボタンです" と書くこともでき、その場合は、「ボタンです」という文字が使われます。なぜ直接書かずに、別ファイルでいちいち定義してるのか?それは、多言語対応するときに便利だからです。例えば日本語と英語バージョンのアプリを作る場合、日本語では「次へ」と定義し、英語では「Next」というふうに定義して簡単に多言語対応ができるようになっています。

<resources>
    <!-- Simple strings. -->
    <string name="skeleton_app">Skeleton App</string>
    <string name="back">Back</string>
    <string name="clear">Clear</string>

    <!-- This is a complex string containing style runs. -->
    <string name="main_label">Hello <u>th<ignore>e</ignore>re</u>, <i>you</i> <b>Activity</b>!</string>
</resources>

59〜62行目
この「ImageView」タグにより、猫の画像が作成されます。(少し見難いですが、BackボタンとClearボタンの間にある変な画像は、よく見ると猫です)

android:id="@+id/image" は ID を指定します。image と定義しています。プログラム内でこのGUIコンポーネントにアクセスするときに使います。プログラムからアクセスしない場合には付ける必要はありません。「@+id/」は、 R.java というリソースを管理するファイルに登録するという意味で、今のところは、必ず付けるものという理解でOKです。

android:layout_width="wrap_content" android:layout_height="wrap_content" は幅と高さを指定します。(もう何度も出てきましたね) wrap_content は自動的に表示に必要な適切なサイズに調整してくれます。

android:paddingLeft="4dip" android_paddingRight="4dip" は左側の余白と右側の余白を設定します。

余白については、こちらに分かりやすくて詳しい情報があるので参考にしてください。
http://androidadvent.blogspot.jp/2011/12/marginpadding.html

android:src="@drawable/violet" は表示する画像を指定します。violet と定義されていますが、res/drawable/violet.jpg が実際の画像です。開いてみると猫の画像が表示されると思います。この画像を例えば犬の画像に入れ替えると当然犬の画像が表示されます。

66〜67行目
この「Button」タグにより Clear ボタンが表示されます。

android:id="@+id/clear" は ID を指定します。clear と定義しています。プログラム内でこのGUIコンポーネントにアクセスするときに使います。プログラムからアクセスしない場合には付ける必要はありません。「@+id/」は、 R.java というリソースを管理するファイルに登録するという意味で、今のところは、必ず付けるものという理解でOKです。

style="@style/ActionButton" は、スタイルを設定します。Back ボタンと同様ですので、そちらを参照してください。このようにスタイルを定義しておけば、同じスタイルのボタンが作れます。あとでボタンのデザインを変更する場合もスタイル定義を変更すればすべてのボタンのスタイルが変更できます。

android:text="@string/claer" はボタンの上に表示される文字を指定します。clear と定義されていますが、これも Back ボタンと同様ですので、そちらを参照してください。

android:textColor="@color/red" は、文字の色を指定します。red と定義されていますが、res/values/colors.xml の中で定義されています。@color は color タグとして定義されているという意味です。ファイル名は何でもよくて、color タグで名前が red として定義されている値 (=#f00) が使われます。#f00 は#RGB の意味で、R=f, G=0, B=0 で赤になります。

color の設定方法は以下の形式で設定します。
#RGB (例:#f0a)
#ARGB (例:#824f)
#RRGGBB (例:#ff08ee)
#AARRGGBB (例:ff0a0b0c)
※ A(α値/透明度), R(赤), G(緑), B(青)

以上で、skeleton_activity.xml の説明は終わりです。
おつかれさまでした。

PS. あえて、説明をしなかった箇所もありますが、長くなるし、ややこしくなるので、必要な箇所のみを説明してあります。

2013年4月26日金曜日

Android サンプルコード徹底解説 - SkeletonApp (Part1)

Android に付属するサンプルコードを徹底解説するコーナー
まず最初は、HelloAndroid と思いきや、これは飛ばして SkeletonApp です。

(1) Eclipse にプロジェクトを作成します。
File > New > Other... と選択します。
Newダイアログが表示されるので、Android > Android Sample Project と選択します。
Build Target で、Android 2.2 を選択します。
Select Sample で、SkeletonApp を選択し、「Finish」ボタンをクリックします。
これで、SkeletonApp プロジェクトが追加されました。
(2) さっそく実行してみます。
SkeletonApp を右クリックし、Run As > Android Application と選択します。
Hello there you Activity! と表示された画面が出てきました。
下の方には、Back と Clear ボタンとボタンの間には変な画像があります。

Clear ボタンを押すと Hello there you Activity! の文字が消えます。
Hello there you Activity! と表示されていた部分を選択しますとキーボードが表示され文字が入力できます。
Back ボタンを押すとアプリケーションが終了します。