チェックボックスの状態を
ボタンを押したときに状態を取得したいと思います
まず前回の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" > <CheckBox android:id="@+id/checkBox_test" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="CheckBox" /> <Button android:id="@+id/button_test" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout>
buttonのidにはbutton_testを割り当てています
次にmainActivityです
package blog.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.Toast; public class TestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //chek_testにid checkBox_testを割り当てている final CheckBox chek_test = (CheckBox)findViewById(R.id.checkBox_test); chek_test.setChecked(true);//初期状態をチェックされた状態に設定 //ボタンの設定 Button b=(Button)findViewById(R.id.button_test); b.setOnClickListener(new View.OnClickListener() { //ボタンを押したとき public void onClick(View v) { if(chek_test.isChecked() == true) { // チェックされた状態だった showMessage("チェックされています"); } else {// チェックされていない状態だった showMessage("チェックされていません"); } } }); } /**トースト設定**/ protected void showMessage(String msg){ Toast.makeText( this, msg, Toast.LENGTH_LONG).show(); } }
ボタンを押したときにisCheckedメソッドでチェック状態を取得しています


スポンサードリンク