Translate

Monday, 29 February 2016

Android AlertDialog Example

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. }  

Output:

android alert dialog example output 1

Friday, 26 February 2016

Android CheckBox Example

android checkbox
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

Wednesday, 24 February 2016

Android ToggleButton Example

android toggle button
Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button.
It is beneficial if user have to change the setting between two states. It can be used to On/Off Sound, Wifi, Bluetooth etc.
Since Android 4.0, there is another type of toggle button called switch that provides slider control.
Android ToggleButton and Switch both are the subclasses of CompoundButton class.

Android ToggleButton class

ToggleButton class provides the facility of creating the toggle button.

XML Attributes of ToggleButton class

The 3 XML attributes of ToggleButton class.
XML AttributeDescription
android:disabledAlphaThe alpha to apply to the indicator when disabled.
android:textOffThe text for the button when it is not checked.
android:textOnThe text for the button when it is checked.

Methods of ToggleButton class

The widely used methods of ToggleButton class are given below.
MethodDescription
CharSequence getTextOff()Returns the text when button is not in the checked state.
CharSequence getTextOn()Returns the text for when button is in the checked state.
void setChecked(boolean checked)Changes the checked state of this button.

Android ToggleButton Example

activity_main.xml

Drag two toggle button and one button for the layout. Now the activity_main.xml file will look 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.     <ToggleButton  
  8.         android:id="@+id/toggleButton1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentLeft="true"  
  12.         android:layout_alignParentTop="true"  
  13.         android:layout_marginLeft="60dp"  
  14.         android:layout_marginTop="18dp"  
  15.         android:text="ToggleButton1"  
  16.         android:textOff="Off"  
  17.         android:textOn="On" />  
  18.   
  19.     <ToggleButton  
  20.         android:id="@+id/toggleButton2"  
  21.         android:layout_width="wrap_content"  
  22.         android:layout_height="wrap_content"  
  23.         android:layout_alignBaseline="@+id/toggleButton1"  
  24.         android:layout_alignBottom="@+id/toggleButton1"  
  25.         android:layout_marginLeft="44dp"  
  26.         android:layout_toRightOf="@+id/toggleButton1"  
  27.         android:text="ToggleButton2"  
  28.         android:textOff="Off"  
  29.         android:textOn="On" />  
  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/toggleButton2"  
  36.         android:layout_marginTop="82dp"  
  37.         android:layout_toRightOf="@+id/toggleButton1"  
  38.         android:text="submit" />  
  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.togglebutton;  
  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.Button;  
  9. import android.widget.Toast;  
  10. import android.widget.ToggleButton;  
  11.   
  12. public class MainActivity extends Activity {  
  13.     private ToggleButton toggleButton1, toggleButton2;  
  14.     private Button buttonSubmit;  
  15.     @Override  
  16.     protected void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.activity_main);  
  19.           
  20.         addListenerOnButtonClick();  
  21.     }  
  22.     public void addListenerOnButtonClick(){  
  23.         //Getting the ToggleButton and Button instance from the layout xml file  
  24.         toggleButton1=(ToggleButton)findViewById(R.id.toggleButton1);  
  25.         toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);  
  26.         buttonSubmit=(Button)findViewById(R.id.button1);  
  27.   
  28.         //Performing action on button click  
  29.         buttonSubmit.setOnClickListener(new OnClickListener(){  
  30.   
  31.             @Override  
  32.             public void onClick(View view) {  
  33.                 StringBuilder result = new StringBuilder();  
  34.                    result.append("ToggleButton1 : ").append(toggleButton1.getText());  
  35.                    result.append("\nToggleButton2 : ").append(toggleButton2.getText());  
  36.                 //Displaying the message in toast  
  37.                 Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG).show();  
  38.             }  
  39.               
  40.         });  
  41.           
  42.     }  
  43.     @Override  
  44.     public boolean onCreateOptionsMenu(Menu menu) {  
  45.         // Inflate the menu; this adds items to the action bar if it is present.  
  46.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  47.         return true;  
  48.     }  
  49.   
  50. }  

Output:

android toggle button example output 1 android toggle button example output 2

Tuesday, 23 February 2016

Android Custom Toast Example

You are able to create custom toast in android. So, you can display some images like congratulations or loss on the toast. It means you are able to customize the toast now.

activity_main.xml

Drag the component that you want to display on the main activity.
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>  

customtoast.xml

Create another xml file inside the layout directory. Here we are having ImageView and TextView in this xml file.
File: customtoast.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  3.       android:id="@+id/custom_toast_layout"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:orientation="vertical"  
  7.     android:background="#F14E23"  
  8.      >  
  9.        
  10.     <ImageView  
  11.         android:id="@+id/custom_toast_image"  
  12.         android:layout_width="wrap_content"  
  13.         android:layout_height="wrap_content"  
  14.         android:contentDescription="@string/hello_world"  
  15.         android:src="@drawable/ic_launcher"/>  
  16.       
  17. <TextView  
  18.         android:id="@+id/custom_toast_message"  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="wrap_content"  
  21.         android:contentDescription="@string/Toast"  
  22.         android:text="@string/Toast" />  
  23. </LinearLayout>  

Activity class

Now write the code to display the custom toast.
File: MainActivity.java
  1. package com.example.customtoast2;  
  2. import android.os.Bundle;  
  3. import android.app.Activity;  
  4. import android.view.Gravity;  
  5. import android.view.LayoutInflater;  
  6. import android.view.Menu;  
  7. import android.view.View;  
  8. import android.view.ViewGroup;  
  9. import android.widget.Toast;  
  10.   
  11. public class MainActivity extends Activity {  
  12.      @Override  
  13.         public void onCreate(Bundle savedInstanceState) {  
  14.             super.onCreate(savedInstanceState);  
  15.             setContentView(R.layout.activity_main);  
  16.               
  17.         //Creating the LayoutInflater instance  
  18.             LayoutInflater li = getLayoutInflater();  
  19.         //Getting the View object as defined in the customtoast.xml file  
  20.             View layout = li.inflate(R.layout.customtoast,  
  21.               (ViewGroup) findViewById(R.id.custom_toast_layout));  
  22.            
  23.         //Creating the Toast object   
  24.             Toast toast = new Toast(getApplicationContext());  
  25.             toast.setDuration(Toast.LENGTH_SHORT);  
  26.             toast.setGravity(Gravity.CENTER_VERTICAL, 00);  
  27.             toast.setView(layout);//setting the view of custom toast layout  
  28.             toast.show();  
  29.         }  
  30.         @Override  
  31.         public boolean onCreateOptionsMenu(Menu menu) {  
  32.             getMenuInflater().inflate(R.menu.activity_main, menu);  
  33.             return true;  
  34.         }  
  35.   
  36. }  

Output:

android custom toast example output 1 android custom toast example output 2

Monday, 22 February 2016

Android Toast Description

android toast
Andorid Toast can be used to display information for the short period of time. A toast contains message to be displayed quickly and disappears after sometime.
The android.widget.Toast class is the subclass of java.lang.Object class.
You can also create custom toast as well for example toast displaying image. You can visit next page to see the code for custom toast.

Toast class

Toast class is used to show notification for a particular interval of time. After sometime it disappears. It doesn't block the user interaction.

Constants of Toast class

There are only 2 constants of Toast class which are given below.
ConstantDescription
public static final int LENGTH_LONGdisplays view for the long duration of time.
public static final int LENGTH_SHORTdisplays view for the short duration of time.

Methods of Toast class

The widely used methods of Toast class are given below.
MethodDescription
public static Toast makeText(Context context, CharSequence text, int duration)makes the toast containing text and duration.
public void show()displays toast.
public void setMargin (float horizontalMargin, float verticalMargin)changes the horizontal and vertical margin difference.

Android Toast Example

  1. Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();  
Another code:
  1. Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT);  
  2. toast.setMargin(50,50);  
  3. toast.show();  
Here, getApplicationContext() method returns the instance of Context.

Full code of activity class displaying Toast

Let's see the code to display the toast.
File: MainActivity.java
  1. package com.example.toast;  
  2. import android.os.Bundle;  
  3. import android.app.Activity;  
  4. import android.view.Menu;  
  5. import android.view.View;  
  6. import android.widget.Toast;  
  7.   
  8. public class MainActivity extends Activity {  
  9.      @Override  
  10.         public void onCreate(Bundle savedInstanceState) {  
  11.             super.onCreate(savedInstanceState);  
  12.             setContentView(R.layout.activity_main);  
  13.               
  14.         //Displaying Toast with Hello Javatpoint message  
  15.             Toast.makeText(getApplicationContext(),"Hello Vikesh",Toast.LENGTH_SHORT).show();  
  16.         }  
  17.   
  18.         @Override  
  19.         public boolean onCreateOptionsMenu(Menu menu) {  
  20.             getMenuInflater().inflate(R.menu.activity_main, menu);  
  21.             return true;  
  22.         }  
  23.   
  24. }  

Friday, 19 February 2016

Android Button Example

android button
Android Button represents a push-button. The android.widget.Button is subclass of TextView class and CompoundButton is the subclass of Button class.
There are different types of buttons in android such as RadioButton, ToggleButton, CompoundButton etc.
Here, we are going to create two textfields and one button for sum of two numbers. If user clicks button, sum of two input values is displayed on the Toast.

Drag the component or write the code for UI in activity_main.xml

First of all, drag 2 textfields from the Text Fields palette and one button from the Form Widgets palette as shown in the following figure.
android button example
The generated code for the ui components will be 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.     <EditText  
  8.         android:id="@+id/editText1"  
  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="24dp"  
  14.         android:ems="10" />  
  15.   
  16.     <EditText  
  17.         android:id="@+id/editText2"  
  18.         android:layout_width="wrap_content"  
  19.         android:layout_height="wrap_content"  
  20.         android:layout_alignLeft="@+id/editText1"  
  21.         android:layout_below="@+id/editText1"  
  22.         android:layout_marginTop="34dp"  
  23.         android:ems="10" >  
  24.   
  25.         <requestFocus />  
  26.     </EditText>  
  27.   
  28.     <Button  
  29.         android:id="@+id/button1"  
  30.         android:layout_width="wrap_content"  
  31.         android:layout_height="wrap_content"  
  32.         android:layout_centerHorizontal="true"  
  33.         android:layout_centerVertical="true"  
  34.         android:text="@string/Button" />  
  35.   
  36. </RelativeLayout>  

Activity class

Now write the code to display the sum of two numbers.
File: MainActivity.java
  1. package com.example.sumof2numbers;  
  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.Button;  
  9. import android.widget.EditText;  
  10. import android.widget.Toast;  
  11.   
  12. public class MainActivity extends Activity {  
  13.     private EditText edittext1,edittext2;  
  14.     private Button buttonSum;  
  15.     @Override  
  16.     protected void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.activity_main);  
  19.           
  20.         addListenerOnButton();  
  21.           
  22.     }  
  23.     public void addListenerOnButton(){  
  24.         edittext1=(EditText)findViewById(R.id.editText1);  
  25.         edittext2=(EditText)findViewById(R.id.editText2);  
  26.         buttonSum=(Button)findViewById(R.id.button1);  
  27.           
  28.         buttonSum.setOnClickListener(new OnClickListener(){  
  29.   
  30.             @Override  
  31.             public void onClick(View view) {  
  32.                 String value1=edittext1.getText().toString();  
  33.                 String value2=edittext2.getText().toString();  
  34.                 int a=Integer.parseInt(value1);  
  35.                 int b=Integer.parseInt(value2);  
  36.                 int sum=a+b;  
  37.     Toast.makeText(getApplicationContext(),String.valueOf(sum),Toast.LENGTH_LONG).show();  
  38.             }  
  39.               
  40.         });  
  41.           
  42.     }  
  43.     @Override  
  44.     public boolean onCreateOptionsMenu(Menu menu) {  
  45.         // Inflate the menu; this adds items to the action bar if it is present.  
  46.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  47.         return true;  
  48.     }  
  49.   
  50. }