Thursday, May 31, 2012

Basic Android tutorial: Using CheckBox in Android


Basic Android tutorial: Using CheckBox in Android
Create a project named MyFavouriteFruitApp.

Change the following files:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="instruction">Please pick your favourite fruit:</string>
    <string name="app_name">FavouriteFruitApp</string>
    <string name="chkAppleLabel">Apple</string>
    <string name="chkOrangeLabel">Orange</string>
    <string name="chkBananaLabel">Banana</string>
</resources>

<?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/instruction" />

    <CheckBox
        android:id="@+id/chkApple"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chkAppleLabel" />

    <CheckBox
        android:id="@+id/chkOrange"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chkOrangeLabel" />

    <CheckBox
        android:id="@+id/chkBanana"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chkBananaLabel" />

</LinearLayout>

package com.kent;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Toast;

public class FavouriteFruitAppActivity extends Activity implements OnClickListener{
           
            private CheckBox chkApple, chkOrange;
           
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        chkApple = (CheckBox) findViewById(R.id.chkApple);
        chkApple.setOnClickListener(this);
        chkOrange = (CheckBox) findViewById(R.id.chkOrange);
        chkOrange.setOnClickListener(this);   
    }


    public void onClick(View v) {
           
            CheckBox chkTemp = (CheckBox) v;
            chkTemp.getText();
           
            if (chkTemp.isChecked()) {
                                   
                        Toast.makeText(FavouriteFruitAppActivity.this,
                        "You have selected " + chkTemp.getText(),
                        Toast.LENGTH_SHORT).show();
            }
    
    }  
}

No comments:

Post a Comment