AndroidでHelloWorld

Kazumi0072008-02-28

Google携帯開発環境であるAndroidに入門中

Javaで開発できる上、開発環境はEclipseエミューレータもWindowsでもMacLinuxといろんな環境で動作するので、いい感じです。

アプリを起動して、「こんにちはアンドロイド」というダイアログを出力するサンプルアプリを書いてみた。

res/layout/main.xmlは以下のとおり。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="アンドロイド" />
	<Button android:id="@+id/button_hello"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="@string/button_click_label" />
</LinearLayout>

Java側でレイアウトを記述することができるけど、xmlに記述するのがAndroid風らしい。

package com.kazumi007.android.sample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class HelloWorld extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main); // 1
		Button button = (Button) findViewById(R.id.button_hello); // 2

		button.setOnClickListener(new View.OnClickListener() { // 3
			public void onClick(View view) {
				new AlertDialog.Builder(HelloWorld.this).setMessage(R.string.message_label) //4
						.setPositiveButton(R.string.close_button_label,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface arg0,
											int arg1) {
									}
								}).show();
			}

		});
	}
}

ソースとしては、
1.リソースを読み込んで、画面を作成
2.ボタンを取り出す。
3.ボタンを押されたときの処理を記述する。今回は匿名クラスで記述。
4.クリックされたときにAlertDialogを表示する
という感じです。

Androidの携帯デバイスがないので今のところは所詮おもちゃ。だけど、デバイスがでてくるといろんなアプリを簡単に作れそうで、とても面白いことになりそうです。