ドキュメント > もしもしAndroid!

「ドキュメント/もしもしAndroid!」の編集履歴(バックアップ)一覧に戻る

ドキュメント/もしもしAndroid! - (2007/11/16 (金) 17:32:13) の編集履歴(バックアップ)


Hello, Android!

第一印象は重要だ。それは、あなたが、このアンドロイドというフレームワークを手にして、"Hello, World!"を書いたときに受ける第一印象だ。そう、アンドロイドにおいて、それはとても簡単なのだ。下記を見て欲しい。

プロジェクトを作成する。

UIを構築する。

コードを走らせる: Hello, Android

以下のセクションでそれをつまびらかに語っていこう。

UIをXMLのレイアウトにアップグレードする。

プロジェクトをデバッグする。

Eclipseなしでプロジェクトを作成する。

さあ行こう。

プロジェクトを作成する

プロジェクトを作成することはできる限り簡単にしてある。Eclipseプラグインで、Androidの開発環境のスナップを作成することが可能だ。Eclipse 3.3以上(Europa)と、Eclipse用のAndroidプラグインは用意してあるかい?それらをインストールしてから次に進んで欲しい。

最初に、"Hello, World!"をビルドするための、簡単な要約を述べておこう。

  1. File->New->Project menuから、"Android Project"を新しく作成する。
  2. New Android Project ダイアログで、プロジェクトの詳細を埋める。
  3. なにかを表示するための自動生成されたテンプレートコードを編集する。

さあ、行こう!以下でそれぞれのステップの詳細を説明しよう。

1.新しい"Android Project"を作成する。

Eclipseから、File->New->Projectと選択して欲しい。もし、EclipseのAndroidプラグインがきちんとインストールされているなら、表示されるダイアログの中に、"Android"と名前のついたフォルダがあり、その中には、"Android Project"があるはずだ。

"Android Project"を選択し、"Next"を押そう。

2.New Android Project ダイアログで、プロジェクトの詳細を埋める。

次の画面で、プロジェクトに関係する詳細を入力する。たとえば次の例のように:

それぞれの入力欄が意味するところは次のようになる。

Project Name プロジェクトを保存したいディレクトリもしくはフォルダの名前
Package Name これはパッケージの名前空間だ。ちょうどJavaのように。あなたのソースコードは全てここより下位におかれるようにする。ここには、自動生成されたスタブのパッケージ名がすでにセットされているはずだ。パッケージ名は、システムにインストールされるすべてのパッケージ間で、ユニークである必要がる。というわけで、あなたのアプリケーションに標準的なドメイン命名スタイルを使うことはとても重要だ。上述の例では、パッケージ名として、ドメイン"com.google.android"を使用している。あなたの所属する組織にみあった、唯一の名前を使用するといいだろう。
Activity Name ここでは、プラグインによって生成されるスタブクラスの名前が書かれている。これは、AndroidのActivityクラスのサブクラスである。Activityは単純なクラスで、それ自体で実行させ、処理させることができる。希望するならUIも作れるが、そうしなくても構わない
Application Name ここにはユーザーが目にするアプリケーションのタイトルを入力する。

"Use default location"チェックボックスをONにすることで、プロジェクトファイルの保存場所を変更することができる。

3.自動生成コードを編集する。

After the plugin runs, you'll have a class named HelloAndroid that looks like this: プラグインを実行すると、下記のような、HelloAndroidクラスが出来上がっているがわかるだろう。

public class HelloAndroid extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.main);
    }
}

次のステップで、これを修正していこう!

UIを構築する。

プロジェクトをセットアップしたあとは、当然、それを修正していく。以下がその完成品だ。1行ずつ解剖していこう。

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        TextView tv = new TextView(this);
        tv.setText("Hello, Android");
        setContentView(tv);
    }
}

このサンプルのコンパイルをするために、インポートセクションに、"import android.widget.TextView;"を追加するしなければらいことを注意しよう。

Androidでは、ユーザーインターフェースは、Viewsと呼ばれるクラス階層で成り立っている。Viewはシンプルな描画オブジェクトである。たとえば、ラジオボタンであるとか、アニメーションであるとか、(今回のケースは)テキストラベルなどだ。テキストを扱えるVieewのサブクラスの名前は、単に、TextViewとなる。

下記が、TextViewクラスを生成する方法だ。

TextView tv = new TextView(this);

TextViewクラスのコンストラクタに渡している引数は、Android Contextのインスタンスである。Contextは単にシステムへ渡すハンドルである。そのハンドルは、リソースを解決したり、データベースや設定などにアクセスするために供給されている。ActivityクラスはContextから派生している。それゆえ、HelloAndroidクラスはActivityクラスのサブクラスであり、コンテキストであるのだ。だから、"this"参照をTextViewに渡すことができる。

一度TextViewを生成してしまえば、何を表示するのか伝えてあげる必要がある。

tv.setText("Hello, Android");

とくに特筆すべきことはないだろう。

ここまでで、TextViewを生成し、どんなテキストをディスプレイに表示すべきかを伝えた。最後のステップは、実際のディスプレイに、TextViewをつなぐことである。こんな感じに。

setContentView(tv);

ActivityのsetContentViewメソッドは、ActivityのUIにどのViewが関連付けられるべきかをシステムに通知する。もし、Activityがこのメソッドをコールしないなら、UIは何も表示されないし、システムは真っ白けの画面を表示することだろう。今のところの目的は、何でもいいからテキストを表示することなので、作ったばかりのTextViewを渡してしまえばよい。

これで、アンドロイドでの"Hello, World"のコーディングは完了だ。もちろん、つぎは、実行させるてみよう。

コードの実行:Hello, Android

Eclipseプラグインのおかげで、とても簡単にあなたのアプリケーションを実行することができる。メニューからRunを選択すると、下のようなダイアログが表示される。

次に、"Android Application"を選択しよう。そして、アイコンの左上をクリックしよう(+印とともに、画面に描画されているやつだ)。それとも、単に、"Android Application"をダブルクリックするだけでいい。"New_configuration"と名づけられた新しいランチャーダイアログが表示されるはずだ。

名前を何か適当なもの、たとえば、"Hello, Android"と変更して、"Browse"ボタンを押下して、あなたのプロジェクトを選択しよう。(もしあなたが2個以上のAndroidプロジェクトをEclipseで開いていたら、正しいものを選択しているかどうか確かめてほしい)プラグインは、自動的に、あなたのプロジェクトからActivityのサブクラスをスキャンして、"Activity:"ラベルの下のドロップダウンリストに追加してくれる。デフォルトでは、あなたは、"Hello, Android"プロジェクトしか作っていないから、単に続けるだけでいい。

"Apply"ボタンを押下しよう。こういう風になる。

これで成功だ。"Run"ボタンを押してみよう。Androidエミュレータがスタートするはずだ。起動完了したら、あなたのアプリケーションが表示されるだろう。今までいったことが全部できていれば、次のような画面を目にすることができるはずだ。

これが、Androidにおける、"Hello, World"だ。とっても簡単だったろう?チュートリアルの次のセクションでは、Androidについて、より詳細な価値ある情報を知ることができるだろう。

UIをXMLレイアウトにアップグレードする。

さっき終わらせた。"Hello, World"サンプルは、いわゆる"programmatic"なUIレイアウトだ。このことは、UI記述をソースコードに直接書いてビルドしているってことだ。UIプログラミングがおわっても、変更にもろいやりかただってことはわかるだろう。たとえば、ちょっとしたUIのレイアウトの変更が、大きなソースコードの変更につながったりとか。Viewクラス同士のつながりは忘れやすいし、それがデバッグに時間を浪費することにつながる。

そんなわけで、Androidでは、もうひとつのUI構築のモデルを提供している。それが、XMLベースのレイアウトファイルだ。このコンセプトを説明するには一例をあげるのが一番だね。ここに、今終わらせたプログラミングベースのものと同じ振る舞いをするXMLレイアウトファイルを用意しよう。

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:text="Hello, Android"/>

たいていの、Andorid XMLレイアウトファイルの構成はシンプルだ。タグのツリーからなっており、それぞれのタグは、Viewクラスの名前になっている。この例で言えば、TextView一要素だけからなる シンプルなツリー構成だ。XMLレイアウトファイルには、タグ名として、Viewクラスを継承したものなら、自作のものでも何でも使える。これは、Webの構築モデルからインスパイアされたものなんだ。ちょうど、UIの表示とデータを処理するアプリケーションロジックを分離できるみたいに。 この例では、4つのXML属性がある。以下が、その意味の要約だ。

Attribute 意味
xmlns:android XMLネームスペース定義だ。これは、Androidネームスペースで定義された、共通の属性を参照するということをAndroidツールに知らせている。
android:layout_width この要素は、このViewが消費する画面幅がどれくらいなのかを定義する要素だ。この場合で言えば、"fill_parent"を使っているが、画面全体の幅を指定しているってことになる。
android:layout_height android:layout_widthto同じようなものだが、これは高さを意味する。
android:text これは、TextViewの内容をセットするものだ。この例でいえば、いつもの"Hello, Android"だ。

そう。XMLレイアウトはざっとこんな感じだ。けど、どうやってそれを組み込むと思う? resディレクトリの下に入れればOKだ。"res"は"resources"をはしょったもので、そのディレクトリには、アプリケーションに必要なコード以外の一式を詰め込んでおけばいい。たとえば、イメージや、ローカライズされた文字列や、XMLレイアウトファイルだ。

Eclipseプラグインは、XMLファイルを作成してくれる。上の例では単にそれを使わなかっただけだ。Package Explorerで、resフォルダの内容を引っ張ってきて、main.xmlファイルに編集して、上のテキストをコピーして、変更を保存しよう。

Package Explorerのソースコードフォルダから、R.javaファイルを開いてみよう。次のようなものが表示されるはずだ。

public final class R {
    public static final class attr {
    };
    public static final class drawable {
        public static final int icon=0x7f020000;
    };
    public static final class layout {
        public static final int main=0x7f030000;
    };
    public static final class string {
        public static final int app_name=0x7f040000;
    };
};

A project's R.java file is an index into all the resources defined in the file. You use this class in your source code as a sort of short-hand way to refer to resources you've included in your project. This is particularly powerful with the code-completion features of IDEs like Eclipse because it lets you quickly and interactively locate the specific reference you're looking for.

The important thing to notice for now is the inner class named "layout", and its member field "main". The Eclipse plugin noticed that you added a new XML layout file and then regenerated this R.java file. As you add other resources to your projects you'll see R.java change to keep up.

The last thing you need to do is modify your HelloAndroid source code to use the new XML version of your UI, instead of the hard-coded version. Here's what your new class will look like. As you can see, the source code becomes much simpler:

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
    }
}

When you make this change, don't just copy-and-paste it in. Try out the code-completion feature on that R class. You'll probably find that it helps a lot.

Now that you've made this change, go ahead and re-run your application — all you need to do is press the green Run arrow icon, or select Run > Run Last Launched from the menu. You should see.... well, exactly the same thing you saw before! After all, the point was to show that the two different layout approaches produce identical results.

There's a lot more to creating these XML layouts, but that's as far as we'll go here. Read the Implementing a User Interface documentation for more information on the power of this approach.

Debugging Your Project

The Android Plugin for Eclipse also has excellent integration with the Eclipse debugger. To demonstrate this, let's introduce a bug into our code. Change your HelloAndroid source code to look like this:

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        Object o = null;
        o.toString();
        setContentView(R.layout.main);
    }
}

This change simply introduces a NullPointerException into your code. If you run your application again, you'll eventually see this:

To find out what went wrong, set a breakpoint in your source code on the line "Object o = null;" (You can do this by double-clicking on the region to the left of the line number in Eclipse.) Then select Run > Debug Last Launched from the menu to enter debug mode. Your app will restart in the emulator, but this time it will suspend when it reaches the breakpoint you set. You can then step through the code in Eclipse's Debug Perspective, just as you would for any other application.

Creating the Project without Eclipse

If you don't use Eclipse (such as if you prefer another IDE, or simply use text editors and command line tools) then the Eclipse plugin can't help you. Don't worry though — you don't lose any functionality just because you don't use Eclipse.

The Android Plugin for Eclipse is really just a wrapper around a set of tools included with the Android SDK. (These tools, like the emulator, aapt, adb, ddms, and others are documented elsewhere.) Thus, it's possible to wrap those tools with another tool, such as an 'ant' build file.

The Android SDK includes a Python script named "activityCreator.py" that can be used to create all the source code and directory stubs for your project, as well as an ant-compatible build.xml file. This allows you to build your project from the command line, or integrate it with the IDE of your choice.

For example, to create a HelloAndroid project similar to the one we just created via Eclipse, you'd use this command:

activityCreator.py --out HelloAndroid com.google.android.hello.HelloAndroid

To build the project, you'd then run the command 'ant'. When that command successfully completes, you'll be left with a file named HelloAndroid.apk under the 'bin' directory. That .apk file is an Android Package, and can be installed and run in your emulator using the 'adb' tool.

For more information on how to use these tools, please read the documentation cited above.

ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。