Sunday, 25 September 2016

Android Spinner

Android Spinner



Android Spinner is like the combox box of AWT or Swing. It can be used to display the multiple options to the user in which only one item can be selected by the user.
Android spinner is like the drop down menu with multiple values from which the end user can select only one value.
Android spinner is associated with AdapterView. So you need to use one of the adapter classes with spinner.
Android Spinner class is the subclass of AsbSpinner class.

Android Spinner Example

In this example, we are going to display the country list. You need to use ArrayAdapter class to store the country list.
Let's see the simple example of spinner in android.

activity_main.xml

Drag the Spinner from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <Spinner  
  8.         android:id="@+id/spinner1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentTop="true"  
  12.         android:layout_centerHorizontal="true"  
  13.         android:layout_marginTop="83dp" />  
  14.   
  15. </RelativeLayout>  


Activity class

Let's write the code to display item on the spinner and perform event handling.
File: MainActivity.java
  1. package com.example.spinner;  
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4. import android.view.Menu;  
  5. import android.view.View;  
  6. import android.widget.AdapterView;  
  7. import android.widget.ArrayAdapter;  
  8. import android.widget.Spinner;  
  9. import android.widget.TextView;  
  10. import android.widget.Toast;  
  11.   
  12. public class MainActivity extends Activity implements  
  13. AdapterView.OnItemSelectedListener {  
  14.   
  15.     String[] country = { "India""USA""China""Japan""Other",  };  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.activity_main);  
  21.         //Getting the instance of Spinner and applying OnItemSelectedListener on it  
  22.         Spinner spin = (Spinner) findViewById(R.id.spinner1);  
  23.         spin.setOnItemSelectedListener(this);  
  24.           
  25.         //Creating the ArrayAdapter instance having the country list  
  26.         ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,country);  
  27.         aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
  28.         //Setting the ArrayAdapter data on the Spinner  
  29.         spin.setAdapter(aa);  
  30.     }  
  31.   
  32.       
  33.     //Performing action onItemSelected and onNothing selected  
  34.     @Override  
  35.     public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {  
  36.         Toast.makeText(getApplicationContext(),country[position] ,Toast.LENGTH_LONG).show();  
  37.     }  
  38.   
  39.     @Override  
  40.     public void onNothingSelected(AdapterView<?> arg0) {  
  41.         // TODO Auto-generated method stub  
  42.           
  43.     }  
  44.   
  45.     @Override  
  46.     public boolean onCreateOptionsMenu(Menu menu) {  
  47.         // Inflate the menu; this adds items to the action bar if it is present.  
  48.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  49.         return true;  
  50.     }  
  51. }  


Output:

android spinner example output 1 android spinner example output 2 android spinner example output 3

Android Alert Dialog

Android Alert Dialog



Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can be used to interrupt and ask the user about his/her choice to continue or discontinue.
Android AlertDialog is composed of three regions: title, content area and action buttons.
Android AlertDialog is the subclass of Dialog class.

Android AlertDialog Example

Let's see a simple example of android alert dialog.

activity_main.xml

You can have multiple components, here we are having only a textview.
File: activity_main.xml
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <TextView  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_centerHorizontal="true"  
  11.         android:layout_centerVertical="true"  
  12.         android:text="@string/hello_world" />  
  13.   
  14. </RelativeLayout>  


strings.xml

Optionally, you can store the dialog message and title in the strings.xml file.
File: strings.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   
  4.     <string name="app_name">alertdialog</string>  
  5.     <string name="hello_world">Hello world!</string>  
  6.     <string name="menu_settings">Settings</string>  
  7.     <string name="dialog_message">Welcome to Alert Dialog</string>  
  8.    
  9.    <string name="dialog_title">Javatpoint Alert Dialog</string>  
  10. </resources>  

Activity class

Let's write the code to create and show the AlertDialog.
File: MainActivity.java
  1. package com.example.alertdialog;  
  2.   
  3. import android.os.Bundle;  
  4. import android.app.Activity;  
  5. import android.app.AlertDialog;  
  6. import android.content.DialogInterface;  
  7. import android.view.Menu;  
  8.   
  9. public class MainActivity extends Activity {  
  10.   
  11.     @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.           
  15.         AlertDialog.Builder builder = new AlertDialog.Builder(this);  
  16.         //Uncomment the below code to Set the message and title from the strings.xml file  
  17.         //builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);  
  18.           
  19.         //Setting message manually and performing action on button click  
  20.         builder.setMessage("Do you want to close this application ?")  
  21.             .setCancelable(false)  
  22.             .setPositiveButton("Yes"new DialogInterface.OnClickListener() {  
  23.                 public void onClick(DialogInterface dialog, int id) {  
  24.                 finish();  
  25.                 }  
  26.             })  
  27.             .setNegativeButton("No"new DialogInterface.OnClickListener() {  
  28.                 public void onClick(DialogInterface dialog, int id) {  
  29.                 //  Action for 'NO' Button  
  30.                 dialog.cancel();  
  31.              }  
  32.             });  
  33.   
  34.         //Creating dialog box  
  35.         AlertDialog alert = builder.create();  
  36.         //Setting the title manually  
  37.         alert.setTitle("AlertDialogExample");  
  38.         alert.show();  
  39.         setContentView(R.layout.activity_main);  
  40.     }  
  41.   
  42.     @Override  
  43.     public boolean onCreateOptionsMenu(Menu menu) {  
  44.         // Inflate the menu; this adds items to the action bar if it is present.  
  45.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  46.         return true;  
  47.     }  
  48.   
  49. }  



Android Check Box

Android Check Box



Android CheckBox is a type of two state button either checked or unchecked.
There can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the user, activate/deactivate the specific action etc.
Android CheckBox class is the subclass of CompoundButton class.

Android CheckBox class

The android.widget.CheckBox class provides the facility of creating the CheckBoxes.

Methods of CheckBox class

There are many inherited methods of View, TextView, and Button classes in the CheckBox class. Some of them are as follows:
MethodDescription
public boolean isChecked()Returns true if it is checked otherwise false.
public void setChecked(boolean status)Changes the state of the CheckBox.


Android CheckBox Example

activity_main.xml

Drag the three checkboxes and one button for the layout. Now the activity_main.xml file will look like this:
File: activity_main.xml
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <CheckBox  
  8.         android:id="@+id/checkBox1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentLeft="true"  
  12.         android:layout_alignParentTop="true"  
  13.         android:text="Pizza" />  
  14.   
  15.     <CheckBox  
  16.         android:id="@+id/checkBox2"  
  17.         android:layout_width="wrap_content"  
  18.         android:layout_height="wrap_content"  
  19.         android:layout_alignParentTop="true"  
  20.         android:layout_toRightOf="@+id/checkBox1"  
  21.         android:text="Coffe" />  
  22.   
  23.     <CheckBox  
  24.         android:id="@+id/checkBox3"  
  25.         android:layout_width="wrap_content"  
  26.         android:layout_height="wrap_content"  
  27.         android:layout_alignParentTop="true"  
  28.         android:layout_toRightOf="@+id/checkBox2"  
  29.         android:text="Burger" />  
  30.   
  31.     <Button  
  32.         android:id="@+id/button1"  
  33.         android:layout_width="wrap_content"  
  34.         android:layout_height="wrap_content"  
  35.         android:layout_below="@+id/checkBox2"  
  36.         android:layout_marginTop="32dp"  
  37.         android:layout_toLeftOf="@+id/checkBox3"  
  38.         android:text="Order" />  
  39.   
  40. </RelativeLayout>  

Activity class

Let's write the code to check which toggle button is ON/OFF.
File: MainActivity.java
  1. package com.example.checkbox;  
  2.   
  3. import android.os.Bundle;  
  4. import android.app.Activity;  
  5. import android.view.Menu;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.*;  
  9.   
  10. public class MainActivity extends Activity {  
  11.     CheckBox pizza,coffe,burger;  
  12.     Button buttonOrder;  
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.activity_main);  
  17.         addListenerOnButtonClick();  
  18.     }  
  19. public void addListenerOnButtonClick(){  
  20.     //Getting instance of CheckBoxes and Button from the activty_main.xml file  
  21.     pizza=(CheckBox)findViewById(R.id.checkBox1);  
  22.     coffe=(CheckBox)findViewById(R.id.checkBox2);  
  23.     burger=(CheckBox)findViewById(R.id.checkBox3);  
  24.     buttonOrder=(Button)findViewById(R.id.button1);  
  25.   
  26.     //Applying the Listener on the Button click  
  27.     buttonOrder.setOnClickListener(new OnClickListener(){  
  28.   
  29.         @Override  
  30.         public void onClick(View view) {  
  31.             int totalamount=0;  
  32.             StringBuilder result=new StringBuilder();  
  33.             result.append("Selected Items:");  
  34.             if(pizza.isChecked()){  
  35.                 result.append("\nPizza 100Rs");  
  36.                 totalamount+=100;  
  37.             }  
  38.             if(coffe.isChecked()){  
  39.                 result.append("\nCoffe 50Rs");  
  40.                 totalamount+=50;  
  41.             }  
  42.             if(burger.isChecked()){  
  43.                 result.append("\nBurger 120Rs");  
  44.                 totalamount+=120;  
  45.             }  
  46.             result.append("\nTotal: "+totalamount+"Rs");  
  47.             //Displaying the message on the toast  
  48.             Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();  
  49.         }  
  50.           
  51.     });  
  52. }  
  53.     @Override  
  54.     public boolean onCreateOptionsMenu(Menu menu) {  
  55.         // Inflate the menu; this adds items to the action bar if it is present.  
  56.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  57.         return true;  
  58.     }  
  59.   
  60. }  


Output:

android checkbox example output 1 android checkbox example output 2