Thursday, July 31, 2014

Use Radio Buttons in Android

Having seen how to use the checkbox, let us now see how to render Radio Buttons in Android. In Android, we can use “android.widget.RadioButton” class to render radio buttons, and those radio buttons are generally grouped by android.widget.RadioGroup. When RadioButtons are in group,only one of them can be selected. If a radio button is previously selected, it gets automatically deselected when some other radio button in the group is clicked.

In this tutorial, we shall learn how to create two radio buttons grouped in a radio group and keep one of them checked by default. When the "Display" button is clicked, a toast message shall appear indicating which radio button is selected.

1. Strings.xml

Open the strings.xml file and add some custom strings to display the data on the screen.
File : res/values/strings.xml

<resources>
   <string name="app_name">MyApp</string>
<string name="radio_Indian">Indian</string>
<string name="radio_nonIndian">Non-Indian</string>
<string name="btn_display">Display</string>
</resources>

2. Add the Radio Button field

Open the main.xml file and add a Radio Group consisting of 2 Radio buttons. We shall also add a button to display which Radio Button is clicked.
File : res/layout/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/textView1"
        android:layout_width="wrap_content"
       android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="What is your nationality?" />
  
<RadioGroup android:id="@+id/radioNationality"
        android:layout_width="wrap_content"
       android:layout_height="wrap_content" >
       
<RadioButton android:id="@+id/radioIndian"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:text="@string/radio_Indian"
            android:checked="true" />
      
<RadioButton android:id="@+id/radioNonIndian"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:text="@string/radio_nonIndian" />
   
</RadioGroup>
   
<Button android:id="@+id/btnDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="@string/btn_display" />
</LinearLayout>
Note: To select a radio button by default, put android:checked="true" within the RadioButton element. Here, radio option “Indian” is selected by default.

3. Java Code

Inside the activity “onCreate()” method, we shall attach a click listener button.
File: HomeScreen.java

package com.endeavour.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class HomeScreen extends Activity {
private RadioGroup radioNatGroup;
private RadioButton radioNatButton;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       addListenerOnButton();
}
public void addListenerOnButton() {
      radioNatGroup = (RadioGroup) findViewById(R.id.radioNationality);
       btnDisplay = (Button) findViewById(R.id.btnDisplay);
       btnDisplay.setOnClickListener(new OnClickListener() {
              @Override
              public void onClick(View v) {
                      // get selected radio button from radioGroup
                     int selectedId = radioNatGroup.getCheckedRadioButtonId();
                     // find the radiobutton by returned id
                      radioNatButton = (RadioButton) findViewById(selectedId);
                     Toast.makeText(HomeScreen.this, radioNatButton.getText(), Toast.LENGTH_SHORT).show();
              }
       });
}
}

4. Output

The following results shall be displayed:

i. When Indian is selected


 ii. When Non-Indian is selected




Use Checkbox in Android

Form controls play an important role in accepting data from the user. We shall see examples of the various form controls one by one. Let's start with the "checkbox".
In Android, we can use “android.widget.CheckBox” class to render a checkbox. In this tutorial, we shall learn how to create 3 checkboxes in XML file, see the use of listener to read the checkbox state – checked or unchecked, and the way to keep a checkbox checked by default.

1. Strings.xml file

Open the strings.xml file and add some user-defined strings to display text on the screen.
File : res/values/strings.xml


<resources>
    <string name="app_name">MyApp</string>
<string name="chk_ios">IPhone</string>
<string name="chk_android">Android</string>
<string name="chk_bb">Blackberry</string>
<string name="btn_display">Display</string>
</resources>

2. Add the checkbox field

Open the main.xml file and add 3 checkboxes and a button (which would show the checkbox state when pressed).
File : res/layout/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/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Which OS do you use?"
        android:textSize="25sp" />
   
<CheckBox android:id="@+id/chkAndroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/chk_android"
        android:textSize="25sp"
        android:checked="true" />
   
<CheckBox android:id="@+id/chkBB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="@string/chk_bb" />
      
<CheckBox android:id="@+id/chkIos"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="@string/chk_ios" />
  
<Button android:id="@+id/btnDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="@string/btn_display" />
</LinearLayout>
Note: To keep a checkbox checked by default, set the android:checked attribute to "true".

3. Java code

We shall now attach listeners inside the activity “onCreate()” method, to monitor the following events :

i. If checkbox id : "chkBB"or “chkIos”  is checked, display a toast message “Try Android Buddy ;)”
ii. If the "Display" button is is clicked, display a toast message and show the checkbox states.
File: HomeScreen.java

package com.endeavour.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class HomeScreen extends Activity {
private CheckBox chkIos, chkAndroid, chkBB;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       addListenerOnChkBB();
       addListenerOnChkIos();
       addListenerOnButton();
}
public void addListenerOnChkIos() {
       chkIos = (CheckBox) findViewById(R.id.chkIos);
       chkIos.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
                //is chkIos checked?
              if (((CheckBox)v).isChecked()) {
                     Toast.makeText(HomeScreen.this,"Try Android Buddy ;)", Toast.LENGTH_LONG).show();
              }
         }
       });
}
public void addListenerOnChkBB() {
       chkBB = (CheckBox) findViewById(R.id.chkBB);
       chkBB.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
                //is chkBB checked?
              if (((CheckBox)v).isChecked()) {
                     Toast.makeText(HomeScreen.this,"Try Android Buddy ;)", Toast.LENGTH_LONG).show();
             }
         }
       });
}
public void addListenerOnButton() {
       chkIos = (CheckBox) findViewById(R.id.chkIos);
       chkAndroid = (CheckBox) findViewById(R.id.chkAndroid);
       chkBB = (CheckBox) findViewById(R.id.chkBB);
       btnDisplay = (Button) findViewById(R.id.btnDisplay);
       btnDisplay.setOnClickListener(new OnClickListener() {
          //Run when button is clicked
         @Override
         public void onClick(View v) {
         StringBuffer result = new StringBuffer();
         result.append("Android check: ").append(chkAndroid.isChecked());
         result.append("\nBlackberry check :").append(chkBB.isChecked());
         result.append("\nIPhone check : ").append(chkIos.isChecked());
         Toast.makeText(HomeScreen.this, result.toString(),Toast.LENGTH_LONG).show();
         }
       });
}
}

4. Output

The following output shall be displayed:

i. When the checkbox for Blackberry is checked


ii. When the Display button is clicked


Monday, July 28, 2014

Password field in Android

Wish to have a Password field in your Android app? You can use “android.widget.EditText“, with inputType="textPassword" to accomplish the task. In this tutorial, we shall learn how to use XML to create a password field, a label field and a normal button. When the button is clicked, the password value will be displayed as a toast message on the screen.

1. Strings.xml file

Open the "strings.xml” file, and add some custom strings.

File : res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MyApp</string>
<string name="lblPassword">Enter Your Password :</string>
<string name="btn_submit">Submit</string>  
</resources>

2. Add the Password field

Open the layout file "main.xml" and add a password component using the EditText field and marking the inputType as "textPassword".

File : res/layout/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/lblPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/lblPassword"
        android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText android:id="@+id/txtPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#EECCFF"
        android:inputType="textPassword" >
<requestFocus />
</EditText>
<Button android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_submit" />
</LinearLayout>

3. Java Code

Inside the activity “onCreate()” method, attach a click listener on button, to display the password value when it is pressed.

File : Main.java

package com.endeavour.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity {

private EditText password;
private Button btnSubmit;

@Override
  public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       addListenerOnButton();
}

public void addListenerOnButton() {
       password = (EditText) findViewById(R.id.txtPassword); 
       btnSubmit = (Button) findViewById(R.id.btnSubmit);
       btnSubmit.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
      Toast.makeText(HomeScreen.this, password.getText(),Toast.LENGTH_SHORT).show();
      }
    });
}
}

4. Output

i. Password field being displayed.


ii. When Password is entered and Submit button is pressed.