main.xmlレイアウトを開きCheckBoxを画面にドラッグドロップします。
CheckBoxのTextプロパティを空にします。
<checkbox
android:id="@+id/CheckBox01"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
</checkbox>
チェックボックスのチェック状態の変化したときの処理を追加します。
まずはMainActivityクラスにandroid.widget.CompoundButton.OnCheckedChangeListenerインターフェースを実装する方法
package my.study.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
public class MainActivity extends Activity implements OnCheckedChangeListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//チェックボックスオブジェクトを取得する
CheckBox chk = (CheckBox)findViewById(R.id.CheckBox01);
//チェックボックスをチェックONにする
chk.setChecked(true);
//チェックボックスにイベントリスナーを設定する
chk.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton cb, boolean isChecked) {
switch(cb.getId()) {
case R.id.CheckBox01:
cb.setText("Checked:" + isChecked);
}
}
}
次は無名クラスを使った方法
package my.study.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//チェックボックスオブジェクトを取得する
CheckBox chk = (CheckBox)findViewById(R.id.CheckBox01);
//チェックボックスをチェックONにする
chk.setChecked(true);
//チェックボックスにイベントリスナーを設定する
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
buttonView.setText("Checked2:" + isChecked);
}
});
}
}
フィールドを利用した方法
package my.study.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//チェックボックスオブジェクトを取得する
CheckBox chk = (CheckBox)findViewById(R.id.CheckBox01);
//チェックボックスをチェックONにする
chk.setChecked(true);
//チェックボックスにイベントリスナーを設定する
chk.setOnCheckedChangeListener(CheckBox01_OnCheckedChangeListener);
}
private CompoundButton.OnCheckedChangeListener CheckBox01_OnCheckedChangeListener =
new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
buttonView.setText("Checked2:" + isChecked);
}
};
}
0 件のコメント:
コメントを投稿