Viewを読み込め!

レイアウトファイルの扱いについて少し書いておく。

レイアウトファイルとは何かというと、オブジェクト(ボタンとかテキストフィールドとか)をどこに配置するかや、
オブジェクトの高さとか幅を初めとする様々な情報を記述するもの。


まずプロジェクトを作ると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="Hello World"
    />
</LinearLayout>


はオブジェクトを直線状に配置するよ、ということを言っている。
次のはそのままテキストを表示するオブジェクトである。


ここでボタンを追加するためには次の記述をの後に加える。

<Button
	id="@+id/button1"
	android:layout_width="100dp"
	android:layout_height="wrap_content"
	android:text="Button"
	/>

これで実行するとボタンが追加されているはずだ。
高さに"wrap_content"を指定しているがこれはそのオブジェクト内のコンテントの大きさに高さを合わせてくれる優れもの。
今回の例では高さはテキストの高さに合わせてくれる。画像を表示する場合はその画像の大きさに合わせてくれるはず。


次に注目するのはidの部分である。これはプログラム中でオブジェクトを呼び出すのに必要となる。
そのため特に呼び出すことがない場合は付ける必要はない。
これを記述した状態でビルドすると"R.java"ファイルの中にidの項目が増えているはずだ。


実際のオブジェクトの呼び出しは、

	Button bt = (Button) findViewById(R.id.button1);

というようにする。"R.id.button1"の部分は自分で決めたidによって変わるので注意。
これで呼び出した後にボタンのクリック時の操作とかを記述すると良いと思う。
Androidではボタンとかチェックボックスとかそういうのは全部Viewを継承(?)しているぽい。


というわけでソースはテキストとボタンを表示し、ボタンを押すとすごい適当なダイアログが出るプログラム。
ダイアログ出すのが簡単だった。


例によって動作画面です。
http://gyazo.com/064f853390e2de15b0def347bdfc29d7.png
http://gyazo.com/7851c672dcb77cadb36463e5625e3f97.png

ButtonTest.java

package net.swelt.android.buttontest;

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

public class ButtonTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        
        Button bt = (Button) findViewById(R.id.button1);
        bt.setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
        		AlertDialog.show(ButtonTest.this, "Title", "Message", "Button", false);
        	}
        });

    }
}

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="Hello World"
    />
<Button
	id="@+id/button1"
	android:layout_width="100dp"
	android:layout_height="wrap_content"
	android:text="Button"
	/>    
</LinearLayout>