Thursday, December 16, 2010

CheckBox Sample

This is an example code for checking the CheckBox.

The code has been written in three files
a) main.xml
b) strings.xml
c) checkActivity.java

The code is as follows

a) main.xml

<?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">
<CheckBox android:id="@+id/check" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="@string/checkboxtest"/>
</LinearLayout>

b) strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
       <string name="app_name">CheckBoxTest</string>
<string name="checkboxtest">Checkbox is unchecked</string>
</resources>

c) checkActivity.java

package org.example.checkbox;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class checkActivity extends Activity implements OnCheckedChangeListener{
/** Called when the activity is first created. */
CheckBox cb;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cb = (CheckBox)findViewById(R.id.check);
cb.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.check:
if(isChecked)
{
cb.setText("Check Box is checked");
}
else
{
cb.setText(R.string.checkboxtest);
}
break;
default:
break;
}
}
}

1 comment: