June 2, 2012

layoutで定義したViewをソースコードで使うためのfindViewById

リソースのlayoutで定義したViewをソースコードから指定して使うには、Activityクラスのメソッドである「findViewById()」を使います。

layoutでViewを定義するときにid(文字列)を設定します。設定は、「@+id/」のあとにid名を付加します。そのidをもとにfindViewByIdで動的に検索してそのViewのインスタンスを取得します。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/launch" />

</LinearLayout>

上記のようにButtonのViewにidを設定します。それをソースコードから呼び出します。

public class SampleAppActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              Toast.makeText(getApplicationContext(), "Hello!", Toast.LENGTH_LONG).show();
          }
        });
    }
}

ポイントはsetContentView()で設定したリソース(main.xml)に対してfindViewByIdでリソースにあるbuttonというidを検索していることです。ですので、setContentViewする前にfindViewByIdを実行するとリソースが見つからず、エラー終了します。

アプリを実行するとmain.xmlで指定したレイアウトでButtonが表示され、そのボタンをクリックするとソースコードで定義した内容が実行されています。


No comments:

Post a Comment