Android : Using CheckBox with Example


Introduction:

In this post we will learn to use checkboxes in Android Application.

What is a CheckBox ?

Checkboxes are the GUI elements which provide facility to select multiple options (from zero to all) from an available list of options. It is very useful while developing any kind of application and Android is not an exception. A CheckBox can have two states i.e, either checked or Unchecked . We can make our logic according to these two states of a checkbox. In general, it can be said that it is not much different from any HTML input(<input type=”checkbox” name=”name1″ value=”value1″ />), ASP.NET checkbox(<asp:CheckBox ID=”CheckBox1″ runat=”server”>) etc. with very few differences.

Pre-requisites :

The reader of this post doesn’t need to have a depth knowledge on Android apps development, in fact this is for beginners who have just started developing android apps and want to know the basics. This post may not help you in real-world project development but, is a short demonstration of CheckBox control in Android.

If you are a beginner and want to know the whole thing right from the start like installing Android SDK and creating your first application etc then you may check these post..

Installing Android SDK on windows – Complete steps

Creating ‘HelloWorld’ application in Android with Eclipse Indigo

Installing [dot]apk file on Emulator in Windows

Simple example of Intent

Using Button & Click-Event with example

CheckBox in Android :

To demonstrate a very simple example using checkbox,  I have dragged a TextView and two CheckBox to my main.xml and did the basic setting-up kind of things like id,text,textColor,background,width,height etc as per my need.

Now create a OnClickListener which will later listen to our on-click events on the two checkboxes. Then put a very simple logic in the onClick method to show text of the checked checkbox(s) in the TextView and let reset the text of the TextView if none of these two checkboxes are checked.

Code :

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" >

<TextView
 android:id="@+id/tvDetails"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_weight="0.17"
 android:textSize="22dp"
 android:background="@android:color/white"
 android:textColor="@android:color/black" />

<CheckBox
 android:id="@+id/cbSuvendu"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="@string/suvendu" />

<CheckBox
 android:id="@+id/cbWordPress"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="@string/wordpress" />

</LinearLayout>

strings.xml


<?xml version="1.0" encoding="utf-8"?>
 <resources>

<string name="hello">Hello World, CheckBoxTutorialActivity!</string>
 <string name="app_name">First CheckBox Tutorial</string>
 <string name="suvendu">www.suvendugiri.com</string>
 <string name="wordpress">www.wordpress.com</string>

</resources>

Activity.java


package com.suvendu.tutorial.cb;

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

public class CheckBoxTutorialActivity extends Activity {
    TextView tv;
    CheckBox cbS;
    CheckBox cbW;
    OnClickListener checkBoxListener;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        cbS=(CheckBox)findViewById(R.id.cbSuvendu);
        cbW=(CheckBox)findViewById(R.id.cbWordPress);
        checkBoxListener =new OnClickListener() {

            @Override
            public void onClick(View v) {
                tv=(TextView)findViewById(R.id.tvDetails);
                tv.setText("I Like ");
     
                if(cbS.isChecked()) {
                    tv.setText(tv.getText().toString()+" "+ cbS.getText().toString());
                }

                if(cbW.isChecked()) {
                    tv.setText(tv.getText().toString()+ " "+cbW.getText().toString());
                }

                if(!cbS.isChecked()&amp;&amp;!cbW.isChecked()) {
                    tv.setText("");
                }
            }
        };

        cbS.setOnClickListener(checkBoxListener);
        cbW.setOnClickListener(checkBoxListener);
    }
}

Download :

You can download the full project here. Download

Or, you can just download the apk here.Download

Conclusion :

Final words- Just download the project and run it using your emulator and if you have any doubts or suggestions, please place them in the comments. In the next post we will see the same example using radio buttons.

Advertisements

Android : Using Button & Click-Event with example


Introduction :

In this article we will learn, how to use Button and Listen for Click-Events. We shall take an example to understand all these . To make the example clear and easy to understand we shall use another control called EditText.

Implementation using  Example :

  • Create a new android project with name ButtonTutorial.
    [If you are a beginner and don’t know how to create a project then read it here Creating HelloWorld Application in Android]
  • Type you application name as My Button Tutorial.
  • Provide package name as com.suvendu.tutorials.button
  • Open main.xml and delete the single TextView already present in the page(may be with a text ‘Hello World, ButtonTutorialActivity!’.
  • Drag a EditText and a Button on to the layout.
  • Change the id of the EditText to ‘@+id/txtShowCurTime
  • Change the id of the Button to ‘@+id/btnGenCurTime
  • Add a new string to strings.xml with Name ‘button’ and Value Generate Current Time
  • Change the text of the Button to ‘@string/button’
    [Your layout is ready now and the main.xml should look like this]

    <?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" >
    
    <EditText
     android:id="@+id/txtShowCurTime"
     android:layout_width="match_parent"
     android:layout_height="wrap_content" >
     <requestFocus />
     </EditText>
    
     <Button
     android:id="@+id/btnGenCurTime"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="@string/button" />
    
    </LinearLayout>
    
    
  • Open your default activity file (Ex: ButtonTutorialActivity.java)
  • Declare two global variables
    Button btnCTime;
     EditText txtCTime;
    
    
  •  import respective packages
    import android.widget.Button;
    import android.widget.EditText;
    
    
  •  Link these variables to the layout in OnCreate() as follows
    btnCTime=(Button)findViewById(R.id.btnGenCurTime);
     txtCTime=(EditText)findViewById(R.id.txtShowCurTime);
    
    
  • We don’t want the OnScreenKeyBoard to appear when the cursor is on EditText so, let disable this.
    txtCTime.setInputType(InputType.TYPE_NULL);
    </li>
    	<li>Set the OnClickListener for the Button
    
    btnCTime.setOnClickListener(new OnClickListener() {
    
     @Override
     public void onClick(View vw) {
    
     }
     });
    
    
  • import the package for OnClickListener
    import android.view.View.OnClickListener;
    
  • Now do the logic inside onClick() to show the current time
    txtCTime.setText(new Date().toString());
    
  • You need to import java package for using Date
    import java.util.Date;
    
  • Finally, the default activity file should look like
    package com.suvendu.tutorials.button;
    
    import java.util.Date;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.text.InputType;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    
    public class ButtonTutorialActivity extends Activity {
        Button btnCTime;
        EditText txtCTime;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            btnCTime=(Button)findViewById(R.id.btnGenCurTime);
            txtCTime=(EditText)findViewById(R.id.txtShowCurTime);
            txtCTime.setInputType(InputType.TYPE_NULL);
            btnCTime.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View vw) {
                    txtCTime.setText(new Date().toString());
                }
            });
        }
    }
    

Downloads :

You can download the full project here. Download

Or, you can just download the apk here.Download

Conclusion :

We are able to use a Button control in Android and can use its OnClick event to do various activities.
I hope  you enjoyed this tutorial.

Please give your valuable feedback and stay tuned for more ..

You may also like-

Simple example of Intent in Android 

If you are a beginner then you may also like following articles-

Android : Simple example of Intent


In this post we will see how to write a simple android application to show usage of Intent.

Steps to be performed :

  • Add a new project
  • Open main.xml and drag and drop three Button controls and then rename their ids.
    Or, Clear all the contents and paste the code provided below.

    
    <?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" >
    
     <Button
     android:id="@+id/btnGallery"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Show My Gallery" />
    
     <Button
     android:id="@+id/btnCallLog"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Show My Call Log" />
    
     <Button
     android:id="@+id/btnContact"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Show My Contacts" />
    
     <Button
     android:id="@+id/btnSearch"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Show My Search" />
    
    </LinearLayout>
    
  • Now lets code for these 4 buttons.
  • Open your Activity file.
  • Now code for each button like the code provided below.
    </pre>
    package com.suvendu.tutorial;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    
    public class IntentDemoActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
    
     Button myGalleryBtn=(Button)findViewById(R.id.btnGallery);
     Button myCallLogBtn=(Button)findViewById(R.id.btnCallLog);
     Button myContactBtn=(Button)findViewById(R.id.btnContact);
     Button mySearchBtn=(Button)findViewById(R.id.btnSearch);
    
     myGalleryBtn.setOnClickListener(new Button.OnClickListener(){
    
    @Override
     public void onClick(View v) {
    
     Intent myIntent=new Intent();
     myIntent.setAction(Intent.ACTION_VIEW);
     myIntent.setData(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
     startActivity(myIntent);
    
     }});
    
     myCallLogBtn.setOnClickListener(new Button.OnClickListener(){
    
    @Override
     public void onClick(View v) {
    
     Intent myIntent=new Intent();
     myIntent.setAction(Intent.ACTION_CALL_BUTTON);
     startActivity(myIntent);
    
     }});
     myContactBtn.setOnClickListener(new Button.OnClickListener(){
    
    @Override
     public void onClick(View v) {
    
     Intent myIntent=new Intent();
     myIntent.setAction(Intent.ACTION_VIEW);
     myIntent.setData(android.provider.Contacts.People.CONTENT_URI);
     startActivity(myIntent);
    
     }});
     mySearchBtn.setOnClickListener(new Button.OnClickListener(){
    
    @Override
     public void onClick(View v) {
    
     Intent myIntent=new Intent();
     myIntent.setAction(Intent.ACTION_SEARCH);
     startActivity(myIntent);
    
     }});
    
     }
    }
    

    [Note: You have to change the package name with your original package name, you provided at the time of creating the project. Similarly, you have to change the class name too.]

Result :

Clicking on the ‘Show My Gallery’ button should open your phone’s gallery.

Clicking on ‘Show My CallLog’ button will open you call log.

Clicking on ‘Show My Contact’ will open your Contact Book.

Clicking on ‘Show My Search’ will open action window to perform search using different options.

Downloads :

If you want to download the code, you can download it here Download

If you want see it quickly you can download it here Download

References :

If you are a beginner then you may also like following articles-

Android: Creating ‘HelloWorld’ application in Android with Eclipse Indigo


Introduction:

Another ‘HelloWorld’ application ???

Yes, the name ‘HelloWorld’ is chosen because it is one of the most searched word when a fresher starts doing a program with a language/platform which is new to him/her. I didn’t really code a great logic for this application except a very few lines of code- just to show some text(lets say: ‘HelloWorld’) on the screen.

Prerequisites:

As I am going to develop an android application so, I need android SDK and Eclipse to be already installed on my system. For a quick installation guide you may read my post on Installing Android SDK on windows: Complete steps.

Target Readers:

I have made this post specially to code on Eclipse Indigo as I assume, the readers of this post are freshers in Android apps development. I am going to explain it right from the New Project dialogue box to   the message on Emulator Screen and I have Eclipse Indigo installed on my system as well. With a different version of Eclipse the code will be same but, the instruction may vary a little bit.

What to Do?

  1. Open Eclipse
  2. Open the Emulator
    [if you don’t have created an AVD then create one using below few steps otherwise you can skip till Step 3]
    *Go to Window menu and click on AVD Manager, which will open Android Virtual Device Manager in  a new window.
    *Click on New button
    *A new window will be opened and will ask for Name.
    *Type a name there.[Ex: MyDevice]
    *Then choose target android version from dropdown Target. [Ex: Android 2.2 -API Level 8]
    *Now click on Create AVD
    *OK, your AVD is now ready to run which you can see in the AVD list on the AVD Manager window.
    *Now, choose the device you just have created and then click on Start button.
  3. Go to File –>New
  4. Click on Project.
  5. Select Android Project from Android directory/folder.
  6. Click Next button.
  7. Type your project name. [Ex: HelloWorld]
  8. Click Next.
  9. Select a build target. [Ex: Android 2.2]
  10. Click Next.
  11. Type a valid Package Name. [Ex: com.demo.mydemo]
  12. Make sure that Create Activity checkbox is checked.
  13. Click Finish.
  14. Now the project can be seen, listed on the Navigator.
  15. It contains some pre-generated files and folders.
  16. Open the Activity file located under src folder .[Ex: src –> com –> demo –> mydemo –>]
  17. Delete the entire contents from it.
  18. Now, Paste following code-
    
    package com.demo.mydemo;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    public class HelloWorldActivity extends Activity {
     TextView tv;
     @Override
     public void onCreate(Bundle bndl) {
     super.onCreate(bndl);
     tv=new TextView(this);
     setContentView(tv);
     tv.setText("This is a simple HelloWorld android application !");
     }
    
    }
    

    [Note: Change the package name if you  have typed a different name earlier while creating project and similarly change the activity name if you have defined with a different name ]

  19. Run the project from menu Run –> Run
    or, right click on the project on Navigator and then click on Run As –> Android Application
  20. Now you can see the result on the emulator screen.

That’s it !!!!

Analysis :
Here package is the one which you have defined earlier while creating the project. Then like Java, you have to import all the classes you reference. The onCreate() method is invoked when the activity starts. To initiate the activity we have to call super.onCreate(). You  need to call super.OnCreate(), every time when overriding the onCreate() method of an Activity. It should be the very first line in the overriding method. Then I have created an instance of TextView, where I am supposed to put some random text or, some message or, “HelloWorld” etc. Here setContentView() sets the TextView, which we have created earlier to the screen so that it can viewed by the user. Then I have assigned some text (i.e,This is a simple HelloWorld android application !”) to the TextView…Yes, I know- I am deviating from the Introduction of the article where I said that it will show ‘HelloWorld’ but, these text doesn’t matters really, what I wanted to show is a custom message or some random text on the emulator screen.  That’s all.

Conclusion :

Now, we are able to create a very simple application in android. I will post some more articles on Android Apps Development in my successive posts.. So, tuned.. In case any query you can comment here.

 

If you want install a .apk file in your emulator then you may read my post here for a easy solution.

https://suvendugiri.wordpress.com/2012/01/24/android-installing-dotapk-file-on-emulator-in-windows/

Android: Installing [dot]apk file on Emulator in Windows


If you want to install a .apk file on your emulator then you need Android Debug Bridge (adb)  which is a command line tool for Android.

Follow few simple steps for installation –

  • Download the required files for adb command line installation from www.suvendugiri.com/AndroidResources/adb.zip
  • Extract and copy all 3 files.
  • Paste to the tools sub-folder of root directory of Android SDK installation
    For Example: In my case – C:\Program Files\Android\android-sdk\tools
  • Start your emulator and wait till home screen has not come.
  • Now open command prompt.
  • Change directory to have the current directory till tool i,e, the folder where you have pasted the 3 extracted files in the above step.
    For Example:  In my case – C:\Program Files\Android\android-sdk\tools
  • Now type :
    adb install E:\AndroidAPKs\MyDemoProject.apk
    Where E:\AndroidAPKs\MyDemoProject.apk is the apk file I wanted to install with it’s detail folder path.
  • Then press enter.

That’s it !!!

[NOTE/DISCLAIMER: ALL THE ABOVE STEPS WORKS FINE FOR ME. BUT, I DON’T TAKE ANY RESPONSIBILITY FOR ANY HARDWARE/SOFTWARE DAMAGE CAUSED DUE TO THIS ARTICLE . YOU SHOULD DO IT ALL WITH YOUR OWN RISK. ]

https://suvendugiri.wordpress.com/2012/01/24/android-installing-dotapk-file-on-emulator-in-windows/

Installing Android SDK on Windows: Complete Steps


To begin with android apps development, you need to install the SDK and some other required components. Following are the steps one may follow to have the Android SDK installed in his/her system, although it is always advised that you should follow the instruction as per developer.android.com. If this not works for you then for any support and help you can mail me on suvendu.giri@live.com

  1. Download and install JDK if not installed already. [Download link] 
  2. Download and install Android SDK. [Download link]
  3. A pop-up will come out just after you finished installing the SDK, which is the SDK manager. If no pop-up window comes then you can manually open it from ‘All Program’.
  4. Download all or, required versions and components by checking them. For example, you can only check Android 2.2 and install it.
  5. Download & install eclipse. [Download link]
    n.b. :this is for 32 bit OS
  6. To Download and install ADT plugin for Eclipse –
    ->Start Eclipse, then select Help > Install New Software….
    ->Click Add, in the top-right corner.
    ->In the Add Repository dialog that appears, enter “ADT Plugin” for the Name and the following URL for the Location.
       

    https://dl-ssl.google.com/android/eclipse/

    ->Click OK
    ->Note: If you have trouble acquiring the plugin, try using “http” in the Location URL, instead of “https” (https is preferred for security reasons).
    ->In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
    ->In the next window, you’ll see a list of the tools to be downloaded. Click Next.
    ->Read and accept the license agreements, then click Finish.
    ->Note: If you get a security warning saying that the authenticity or validity of the software can’t be established, click OK.
    ->When the installation completes, restart Eclipse.

  7. Configuring Android SDK:
    ->After you’ve successfully downloaded the ADT as described above, the next step is to modify your ADT preferences in Eclipse to point to the Android SDK directory:Select Window > Preferences… to open the Preferences panel (Mac OS X: Eclipse > Preferences).
    Select Android from the left panel.
    ->You may see a dialog asking whether you want to send usage statistics to Google. If so, make your choice and click Proceed. You cannot continue with this procedure until you click Proceed.
    ->For the SDK Location in the main panel, click Browse… and locate your downloaded SDK directory.
    ->Click Apply, then OK.
    ->Done! If you haven’t encountered any problems, then the installation is complete