Javaソースコードの修正
画面に追加した TextView を Java ソースコードから操作してみます。
● res/layout/main.xml を以下のようにしたとします。
<?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/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
● src/com/test/sample/SampleActivity.java を開き、青字部分を追記します。
xml に書かれた id から TextView を取得し、文字列を書き換えています。
package com.test.sample;
import android.app.Activity;
import android.os.Bundle;
public class SampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// テキストビューを取得
TextView textView1 = (TextView)this.findViewById(R.id.textView1);
// テキストビューへ文字列をセット
textView1.setText("TEST");
}
}
● TextViewの部分へ赤線が引かれますのでTextView上をマウスオーバーし、
「'TextView' をインポートします (android.widget)」 をクリックします。
● 青字部分が追加され、赤線が消えます。
package com.test.sample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// テキストビューを取得
TextView textView1 = (TextView)this.findViewById(R.id.textView1);
// テキストビューへ文字列をセット
textView1.setText("TEST");
}
}
かなり単純な処理ですが、これにてソースコードからの操作は完了とします。
基本的に id を元に View を取得し、そのViewに対して関数を用いて処理をすることはどんな View でも同じです。