Friday, June 1, 2012

Basic Android App Development: CheckBox Example 3


 
Create android project MyFavouriteFruitApp.
Copy a banana image to res/drawable-hdpi directory.
Then copy 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="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/chkBanana"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chkBananaLabel" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</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.ImageView;
import android.widget.Toast;

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


    public void onClick(View v) {
           
            CheckBox chkTemp = (CheckBox) v;
           
            ImageView imgView = (ImageView) findViewById(R.id.imageView1);
           
            if(!chkTemp.isChecked()){
                        Toast.makeText(FavouriteFruitAppActivity.this,
                        "Now you don't like " + chkTemp.getText(),
                        Toast.LENGTH_SHORT).show();
                       
                        imgView.setImageResource(android.R.color.transparent);
            }
           
            else {
                                   
                        Toast.makeText(FavouriteFruitAppActivity.this,
                        "Ohh...You likes " + chkTemp.getText(),
                        Toast.LENGTH_SHORT).show();
                       
                        imgView.setImageResource(R.drawable.banana);

        }
    
    }  
}

No comments:

Post a Comment