Thursday, October 22, 2009

CheckBox

A checkbox is a specific type of two-states button that can be either checked or unchecked.



Modify the main.xml with two CheckBox and a Button.
<?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="@string/hello"
/>
<CheckBox
android:id="@+id/option1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Option 1"
/>
<CheckBox
android:id="@+id/option2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Option 2"
/>
<Button
android:id="@+id/OK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="OK"
/>
</LinearLayout>


Modify the code to read and show the CheckBox's status.
package com.exercise.AndroidCheckBox;

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 AndroidCheckBox extends Activity {

CheckBox myOption1, myOption2;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

myOption1 = (CheckBox)findViewById(R.id.option1);
myOption2 = (CheckBox)findViewById(R.id.option2);
Button myOK = (Button)findViewById(R.id.OK);
myOK.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(AndroidCheckBox.this,
(CharSequence)(
"Option1 = " + myOption1.isChecked() +
" " +
"Option2 = " + myOption2.isChecked()),
Toast.LENGTH_LONG).show();
}

});

}
}


Download the files.

No comments:

Post a Comment