Android Examples

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 117

Android AutoCompleteTextView with Examples

AutoCompleteTextView is an editable text view which is used to show the list of suggestions based
on the user typing text.

The AutoCompleteTextView is a subclass of EditText class so we can inherit all the properties


of EditText in AutoCompleteTextView based on our requirements.

The Threshold property of AutoCompleteTextView is used to define the minimum number of


characters the user must type to see the list of suggestions.

setAdapter() : binding the data to AutoCompleteTextView control 

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:orientation="vertical"
    android:id="@+id/linear_Layout">
    <AutoCompleteTextView
        android:id="@+id/ac_Country"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:hint="Enter Country Name"/>
</LinearLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    String[] Countries =
{ "India", "USA", "Australia", "UK", "Italy", "Ireland", "Africa" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, Countries);
        AutoCompleteTextView actv =
(AutoCompleteTextView)findViewById(R.id.ac_Country);
        actv.setThreshold(1);
        actv.setAdapter(adapter);
        actv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
            @Override
            public void onItemClick(AdapterView<?> parent, View
view, int position, long id) {
                Toast.makeText(getApplicationContext(), "Selected Item:
" + parent.getItemAtPosition(position) , Toast.LENGTH_SHORT).show();
            }
        });
    }
}
Android Toggle Button with Examples

Toggle Button is a user interface control which is used to display ON (Checked) or OFF(Unchecked)


states as a button with a light indicator.

By default, the android ToggleButton will be in OFF (Unchecked) state.  if we want to change the


state of ToggleButton to ON (Checked), then we need to set android:checked = “true” in our XML
layout file.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
 android:layout_width="match_parent" android:layout_height="match_parent"
>
    <ToggleButton
        android:id="@+id/toggle1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="120dp"
        android:checked="true"
        android:textOff="OFF"
        android:textOn="ON"/>
    <ToggleButton
        android:id="@+id/toggle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/toggle1"
        android:layout_toRightOf="@+id/toggle1"
        android:textOff="OFF"
        android:textOn ="ON"/>
    <Button
        android:id="@+id/getBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="150dp"
        android:layout_marginTop="200dp"
        android:text="Submit" />
</RelativeLayout>
MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ToggleButton tb1 =
(ToggleButton)findViewById(R.id.toggle1);
        final ToggleButton tb2 =
(ToggleButton)findViewById(R.id.toggle2);
        Button btnGet = (Button)findViewById(R.id.getBtn);
        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Toggle Button1
-  " + tb1.getText().toString() + " \n" + "Toggle Button2 -
" + tb2.getText().toString(),Toast.LENGTH_SHORT).show();
            }
        });
    }
}
Android CheckBox with Examples
CheckBox is a two states button that can be either checked (ON) or unchecked (OFF) and it will
allow users to toggle between the two states (ON / OFF) based on the requirements.

By default, the android CheckBox will be in OFF (Unchecked) state. We can change the default state
of CheckBox by using android:checked attribute.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <CheckBox
        android:id="@+id/chkJava"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginTop="150dp"
        android:layout_marginLeft="100dp"
        android:text="Java"
        android:onClick="onCheckboxClicked"/>
    <CheckBox
        android:id="@+id/chkPython"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Python"
        android:onClick="onCheckboxClicked"/>
    <CheckBox
        android:id="@+id/chkAndroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Android"
        android:onClick="onCheckboxClicked"/>
    <CheckBox
        android:id="@+id/chkAngular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="AngularJS"
        android:onClick="onCheckboxClicked"/>
    <Button
        android:id="@+id/getBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:text="Get Details" />
</LinearLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    CheckBox android, java, angular, python;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        android = (CheckBox)findViewById(R.id.chkAndroid);
        angular = (CheckBox)findViewById(R.id.chkAngular);
        java = (CheckBox)findViewById(R.id.chkJava);
        python = (CheckBox)findViewById(R.id.chkPython);
        Button btn = (Button)findViewById(R.id.getBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = "Selected Courses";
                if(android.isChecked()){
                result += "\nAndroid";
                }
                if(angular.isChecked()){
                    result += "\nAngularJS";
                }
                if(java.isChecked()){
                    result += "\nJava";
                }
                if(python.isChecked()){
                    result += "\nPython";
                }
                Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void onCheckboxClicked(View view) {
        boolean checked = ((CheckBox) view).isChecked();
        String str="";
        // Check which checkbox was clicked
        switch(view.getId()) {
            case R.id.chkAndroid:
                str = checked?"Android Selected":"Android Deselected";
                break;
            case R.id.chkAngular:
                str = checked?"AngularJS Selected":"AngularJS
Deselected";
                break;
            case R.id.chkJava:
                str = checked?"Java Selected":"Java Deselected";
                break;
            case R.id.chkPython:
                str = checked?"Python Selected":"Python Deselected";
                break;
        }
        Toast.makeText(getApplicationContext(), str,
Toast.LENGTH_SHORT).show();
    }
}
Android RadioButton with Examples
Radio Button is a two states button that can be either checked or unchecked and it’s a same
as CheckBox control, except that it will allow only one option to select from the group of options.

In android, we use radio buttons with in a RadioGroup to combine multiple radio buttons into one
group and it will make sure that user can select only one option from the group of multiple options.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:layout_marginLeft="100dp"
        android:textSize="18dp"
        android:text="Select Your Course"
        android:textStyle="bold"
        android:id="@+id/txtView"/>
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/rdGroup"
    android:layout_below="@+id/txtView">
    <RadioButton
        android:id="@+id/rdbJava"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Java"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbPython"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Python"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbAndroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Android"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbAngular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="AngularJS"
        android:onClick="onRadioButtonClicked"/>
</RadioGroup>
    <Button
        android:id="@+id/getBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_below="@+id/rdGroup"
        android:text="Get Course" />
</RelativeLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    RadioButton android, java, angular, python;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        android = (RadioButton)findViewById(R.id.rdbAndroid);
        angular = (RadioButton)findViewById(R.id.rdbAngular);
        java = (RadioButton)findViewById(R.id.rdbJava);
        python = (RadioButton)findViewById(R.id.rdbPython);
        Button btn = (Button)findViewById(R.id.getBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = "Selected Course: ";
                result+= (android.isChecked())?"Android":
(angular.isChecked())?"AngularJS":(java.isChecked())?"Java":
(python.isChecked())?"Python":"";
                Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void onRadioButtonClicked(View view) {
        boolean checked = ((RadioButton) view).isChecked();
        String str="";
        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.rdbAndroid:
                if(checked)
                str = "Android Selected";
                break;
            case R.id.rdbAngular:
                if(checked)
                str = "AngularJS Selected";
                break;
            case R.id.rdbJava:
                if(checked)
                str = "Java Selected";
                break;
            case R.id.rdbPython:
                if(checked)
                str = "Python Selected";
                break;
        }
        Toast.makeText(getApplicationContext(), str,
Toast.LENGTH_SHORT).show();
    }
}
Android ProgressBar with Examples

ProgressBar is a user interface control which is used to indicate the progress of an operation. For
example, downloading a file, uploading a file.

By default the ProgressBar will be displayed as a spinning wheel, in case if we want to show it like
horizontal bar then we need to change the style property to horizontal like style="?
android:attr/progressBarStyleHorizontal".

In anroid, the ProgressBar supports two types of modes to show the progress, those
are Determinate and Indeterminate.

Android ProgressBar with Determinate Mode

Generally, we use the Determinate progress mode in progress bar when we want to show the
quantity of progress has occurred. For example, the percentage of file downloaded, number of
records inserted into database, etc.
 
To use Determinate progress, we need to set the style of progress bar
to Widget_ProgressBar_Horizontal or progressBarStyleHorizontal and set the amount of
progress using android:progress attribute.
 
Following is the example which shows a Determinate progress bar that is 50% completes.

<ProgressBar
    android:id="@+id/pBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:max="100"
    android:progress="50" />

By using setProgress(int) method, we can update the percentage of progress displayed in app or by


calling incrementProgressBy(int) method, we can increase the value of current progress completed
based on our requirements. 
 
Generally, when the progress value reaches 100 then the progress bar is full. By
using android:maxattribute we can adjust this default value. 
Android ProgressBar with Indeterminate Mode

Generally, we use the Indeterminate progress mode in progress bar when we don’t know how long
an operation will take or how much work has done.
 
In indeterminate mode the actual progress will not be shown, only the cyclic animation will be shown
to indicate that some progress is happing like as shown in above progress bar loading images.
 
By using progressBar.setIndeterminate(true) in activity file programmatically or
using android:indeterminate = “true” attribute in XML layout file, we can
enable Indeterminate progress mode.
 
Following is the example to set Indeterminate progress mode in XML layout file.

<ProgressBar
    android:id="@+id/progressBar1"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminate="true"/>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
    <ProgressBar
        android:id="@+id/pBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="200dp"
        android:minHeight="50dp"
        android:minWidth="200dp"
        android:max="100"
        android:indeterminate="false"
        android:progress="0" />
    <TextView
        android:id="@+id/tView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/pBar"
        android:layout_below="@+id/pBar" />
    <Button
        android:id="@+id/btnShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="130dp"
        android:layout_marginTop="20dp"
        android:text="Start Progress"
        android:layout_below="@+id/tView"/>
</RelativeLayout>

MainActivity.java

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private ProgressBar pgsBar;
    private int i = 0;
    private TextView txtView;
    private Handler hdlr = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pgsBar = (ProgressBar) findViewById(R.id.pBar);
        txtView = (TextView) findViewById(R.id.tView);
        Button btn = (Button)findViewById(R.id.btnShow);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i = pgsBar.getProgress();
                new Thread(new Runnable() {
                    public void run() {
                        while (i < 100) {
                            i += 1;
                            // Update the progress bar and display the
current value in text view
                            hdlr.post(new Runnable() {
                                public void run() {
                                    pgsBar.setProgress(i);
                                    txtView.setText(i+"/"+pgsBar.getMax()
);
                                }
                            });
                            try {
                                // Sleep for 100 milliseconds to show the
progress slowly.
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        });
    }
}
Android Spinner (Dropdown List) with Examples
Spinner is a view which allow a user to select one value from the list of values. The spinner in
android will behave same like dropdown list in other programming languages.

Generally, the android spinners will provide a quick way to select one item from the list of values and
it will show a dropdown menu with a list of all values when we click or tap on it.
 
By default, the android spinner will show its currently selected value and by using Adapter we can
bind the items to spinner object.

We can populate our Spinner control with list of choices by defining an ArrayAdapter in our Activity


file.
 
Generally, the Adapter pulls data from a sources such as an array or database and converts each
item into a result view and that’s placed into the list.

Android Adapter

In android, Adapter will act as an intermediate between the data sources and adapter views such
as ListView, Gridview to fill the data into adapter views. The adapter will hold the data and iterates
through an items in data set and generate the views for each item in the list.
 
Generally, in android we have a different types of adapters available to fetch the data from different
data sources to fill the data into adapter views, those are

Adapter Description

ArrayAdapter It will expects an Array or List as input.

CurosrAdapter It will accepts an instance of cursor as an input.

SimpleAdapte It will accepts a static data defined in the resources.


r

BaseAdapter It is a generic implementation for all three adapter types and it can be used for
ListView, Gridview or Spinners based on our requirements
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
    <TextView
        android:id="@+id/txtVw"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="150dp"
        android:text="Select User:"
        android:textStyle="bold"
        android:textSize="15dp" />
    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/txtVw"
        android:layout_toRightOf="@+id/txtVw" />
</RelativeLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public
class MainActivity extends AppCompatActivity implements AdapterView.OnIte
mSelectedListener {
String[] users = { "John David", "Ram Dixit", "Sham Joshi", "Pavan
Kumar", "Sai Baba" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner spin = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, users);
       
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_
item);
        spin.setAdapter(adapter);
        spin.setOnItemSelectedListener(this);
    }
    @Override
    public void onItemSelected(AdapterView<?> arg0, View
arg1, int position,long id) {
        Toast.makeText(getApplicationContext(), "Selected User:
"+users[position] ,Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO - Custom Code
    }
}
Android DatePicker with Examples
In android, DatePicker is a control which will allow users to select the date by day, month and year
in our application user interface.
 
<DatePicker android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Android DatePicker with Calendar Mode

We can define android DatePicker to show only calendar view by using


DatePicker android:datePickerMode attribute.

<DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:datePickerMode="calendar"/>

Android DatePicker with Spinner Mode

If we want to show the DatePicker in spinner format like showing day, month and year separately to
select the date, then by using DatePicker android:datePickerMode attribute we can achieve this.

<DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:datePickerMode="spinner"/>

To get only spinner mode date selection, then we need to


set android:calendarViewShown="false" attribute in DatePicker control like as shown below.

<DatePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:datePickerMode="spinner"
    android:calendarViewShown="false"/>
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
    <DatePicker
        android:id="@+id/datePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/datePicker1"
        android:layout_marginLeft="100dp"
        android:text="Get Date" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="10dp"
        android:textStyle="bold"
        android:textSize="18dp"/>
</RelativeLayout>

MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    DatePicker picker;
    Button btnGet;
    TextView tvw;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvw=(TextView)findViewById(R.id.textView1);
        picker=(DatePicker)findViewById(R.id.datePicker1);
        btnGet=(Button)findViewById(R.id.button1);
        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvw.setText("Selected Date: "+ picker.getDayOfMonth()
+"/"+ (picker.getMonth() + 1)+"/"+picker.getYear());
            }
        });
    }
}

Android Show DatePicker on EditText Click Example


Following is the example of open or popup datepicker dialog when we click on EditText control and
get the selected date value on Button click in android application.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="150dp"
        android:ems="10"
        android:hint="Enter Date" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_marginLeft="100dp"
        android:text="Get Date" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="10dp"
        android:textStyle="bold"
        android:textSize="18dp"/>
</RelativeLayout>

MainActivity.java

import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
    DatePickerDialog picker;
    EditText eText;
    Button btnGet;
    TextView tvw;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvw=(TextView)findViewById(R.id.textView1);
        eText=(EditText) findViewById(R.id.editText1);
        eText.setInputType(InputType.TYPE_NULL);
        eText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar cldr = Calendar.getInstance();
                int day = cldr.get(Calendar.DAY_OF_MONTH);
                int month = cldr.get(Calendar.MONTH);
                int year = cldr.get(Calendar.YEAR);
                // date picker dialog
                picker = new DatePickerDialog(MainActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker
view, int year, int monthOfYear, int dayOfMonth) {
                                eText.setText(dayOfMonth + "/" +
(monthOfYear + 1) + "/" + year);
                            }
                        }, year, month, day);
                picker.show();
            }
        });
        btnGet=(Button)findViewById(R.id.button1);
        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvw.setText("Selected Date: "+ eText.getText());
            }
        });
    }
}
Android TimePicker with Examples
In android, TimePicker is a widget for selecting the time of day, in either 24-hour or AM/PM mode.

<TimePicker android:id="@+id/timePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Generally, in android TimePicker available in two modes, one is to show the time in clock mode and
another one is to show the time in spinner mode.

Following is the example of showing the TimePicker in Clock mode.

<TimePicker android:id="@+id/timePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:timePickerMode="clock" />

Following is the example of showing the TimePicker in spinner mode.

<TimePicker
    android:id="@+id/datePicker1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:timePickerMode="spinner"/>

We can change the TimePicker in spinner mode to AM / PM format instead of 24 Hours format by


using setIs24HourView(true) method in Activity file like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
    <TimePicker
        android:id="@+id/timePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/timePicker1"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="160dp"
        android:text="Get Date" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_marginLeft="120dp"
        android:layout_marginTop="10dp"
        android:textStyle="bold"
        android:textSize="18dp"/>
</RelativeLayout>

MainActivity.java
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends AppCompatActivity {
    TimePicker picker;
    Button btnGet;
    TextView tvw;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvw=(TextView)findViewById(R.id.textView1);
        picker=(TimePicker)findViewById(R.id.timePicker1);
        picker.setIs24HourView(true);
        btnGet=(Button)findViewById(R.id.button1);
        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int hour, minute;
                String am_pm;
                if (Build.VERSION.SDK_INT >= 23 ){
                    hour = picker.getHour();
                    minute = picker.getMinute();
                }
                else{
                    hour = picker.getCurrentHour();
                    minute = picker.getCurrentMinute();
                }
                if(hour > 12) {
                    am_pm = "PM";
                    hour = hour - 12;
                }
                else
                {
                    am_pm="AM";
                }
                tvw.setText("Selected Date: "+ hour +":"+ minute+"
"+am_pm);
            }
        });
    }
}
Android Show TimePicker on EditText Click Example

Following is the example of open or popup timepicker dialog when we click on EditText control and
get the selected time value on Button click in android application.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="150dp"
        android:ems="10"
        android:hint="Enter Time" />
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_marginLeft="100dp"
        android:text="Get Date" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="10dp"
        android:textStyle="bold"
        android:textSize="18dp"/>
</RelativeLayout>

MainActivity.java

import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {
    TimePickerDialog picker;
    EditText eText;
    Button btnGet;
    TextView tvw;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvw=(TextView)findViewById(R.id.textView1);
        eText=(EditText) findViewById(R.id.editText1);
        eText.setInputType(InputType.TYPE_NULL);
        eText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar cldr = Calendar.getInstance();
                int hour = cldr.get(Calendar.HOUR_OF_DAY);
                int minutes = cldr.get(Calendar.MINUTE);
                // time picker dialog
                picker = new TimePickerDialog(MainActivity.this,
                        new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker
tp, int sHour, int sMinute) {
                                eText.setText(sHour + ":" + sMinute);
                            }
                        }, hour, minutes, true);
                picker.show();
            }
        });
        btnGet=(Button)findViewById(R.id.button1);
        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvw.setText("Selected Time: "+ eText.getText());
            }
        });
    }
}
Android SeekBar with Examples
In android, SeekBar is an extension of ProgressBar control with a draggable thumb. The SeekBar
allow users to touch the thumb and drag left or right to set the current progress levels.
 
The android SeekBar is a one of the useful UI element and it provide a user interface to select the
integer values within the defined range.

An example of SeekBar is our device Brightness control or volume control.


 
In android, by using SeekBar.OnSeekBarChangeListener listener we can notify the client, when the
progress level of seekbar has been changed.

In anroid, the SeekBar supports two types of modes to show the progress, those
are Determinate and Indeterminate.

Android SeekBar with Determinate Mode

Determinate progress mode in seekbar when we want to show the quantity of progress has
occurred. For example, the percentage of file downloaded, number of records inserted into database,
etc.

Following is the example which shows a Determinate seekbar that is 50% completes.

<SeekBar
    android:id="@+id/seekBar1"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:max="100"
    android:progress="50" />

Android SeekBar with Indeterminate Mode

Indeterminate progress mode in seekbar when we don’t know how long an operation will take or
how much work has done.

In indeterminate mode the actual progress will not be shown, only the cyclic animation will be shown
to indicate that some progress is happing.

<SeekBar android:id="@+id/seekBar1"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:max="100"
    android:indeterminate="true"
    android:progress="0" />

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="200dp"
        android:max="100"
        android:indeterminate="false"
        android:progress="0" />
    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/seekBar1"
        android:layout_below="@+id/seekBar1"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="130dp"
        android:textSize="20dp"
        android:textStyle="bold"/>
</RelativeLayout>

MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private SeekBar sBar;
    private TextView tView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sBar = (SeekBar) findViewById(R.id.seekBar1);
        tView = (TextView) findViewById(R.id.textview1);
        tView.setText(sBar.getProgress() + "/" + sBar.getMax());
        sBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListen
er() {
            int pval = 0;
            @Override
            public void onProgressChanged(SeekBar
seekBar, int progress, boolean fromUser) {
                pval = progress;
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            //write custom code to on start progress 
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                tView.setText(pval + "/" + seekBar.getMax());
            }
        });
    }
}
Android RatingBar with Examples
In android, RatingBar is a UI control which is used to get the rating from the user. The RatingBar is
an extension of SeekBar and ProgressBar that shows a rating in stars and it allow users to set the
rating value by touch or click on the stars.
 
The android RatingBar will always return a rating value as floating point number such as 1.0, 2.0, 2.5,
3.0, 3.5, etc.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="80dp"
        android:layout_marginTop="200dp"
        android:numStars="5"
        android:rating="3.5"/>
    <Button
        android:id="@+id/btnGet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/ratingBar1"
        android:layout_below="@+id/ratingBar1"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="60dp"
        android:text="Get Rating"/>
    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnGet"
        android:layout_below="@+id/btnGet"
        android:layout_marginTop="20dp"
        android:textSize="20dp"
        android:textStyle="bold"/>
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private RatingBar rBar;
    private TextView tView;
    private Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rBar = (RatingBar) findViewById(R.id.ratingBar1);
        tView = (TextView) findViewById(R.id.textview1);
        btn = (Button)findViewById(R.id.btnGet);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int noofstars = rBar.getNumStars();
                float getrating = rBar.getRating();
                tView.setText("Rating: "+getrating+"/"+noofstars);
            }
        });
    }
}
Android TextClock with Examples
In android, TextClock is a UI control which is used to show the current date or time as a formatted
string.

By using is24HourModeEnabled() method, we can easily know that whether the system using


TextClock in 24 Hours format or 12 Hours format.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
    <TextClock
        android:id="@+id/textClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="70dp"
        android:format12Hour="hh:mm:ss a"
        android:textColor="#F1511B"
        android:textSize="45dp"
        android:textStyle="bold" />
    <TextClock
        android:id="@+id/textClock2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="100dp"
        android:layout_below="@+id/textClock1"
        android:textColor="#80CC28"
        android:textSize="45dp"
        android:textStyle="bold" />
    <Button
        android:id="@+id/btnGet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textClock2"
        android:layout_below="@+id/textClock2"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="40dp"
        android:text="Get Time"/>
    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnGet"
        android:layout_below="@+id/btnGet"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="-30dp"
        android:textSize="20dp"
        android:textStyle="bold"/>
</RelativeLayout>

The android TextClock has been introduced in API Level 17 so if we use TextClock in our app then it
requires a minimum API Level 17. In case if your app SDK version less than 17 then TextClock will
throw an error like “View Required API Level 17”.

To fix this error we need to update SDK version of our app for that just double click
on build.gradle(Module: app) file in application and update minSDKVersion to 17 or more and
click SyncNow

MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextClock;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextClock tClock;
    private TextView tView;
    private Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tClock = (TextClock) findViewById(R.id.textClock1);
        tView = (TextView) findViewById(R.id.textview1);
        btn = (Button)findViewById(R.id.btnGet);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tView.setText("Time: "+tClock.getText());
            }
        });
    }
}

Android AlertDialog with Examples


In android, Dialog is a small window that prompt messages to the user to make a decision or enter
additional details. Generally, the Dialogs are used with modals event and these useful to prompt
users to perform a particular action to proceed further in application.

In android, we have a different type of Dialogs available, those are


 
Dialog Description

AlertDialog This dialog is used to display prompt to the user with title, upto three buttons,
list of selectable items or a custom layout.

DatePickerDialog This dialog is a predefined UI control and it allow user to select Date.

TimePickerDialo It’s a predefined UI control and it allow user to select Time.


g

Android AlertDialog
In android, AlertDialog is used to prompt a dialog to the user with message and buttons to perform
an action to proceed further.
 
The AlertDialog in android application will contain a three regions like as shown below.
 
 
In android Alert Dialogs, we can show a title, up to three buttons, a list of selectable items or a
custom layout based on our requirements.
 
Region Description

Title It’s an optional and it can be used to show the detailed messages based on our
requirements.

Content It is used to display a message, list or other custom layouts based on our
Area requirements.

Action It is used to display an action buttons to interact with the users. We can use upto 3
Buttons different action buttons in alert dialog, such as positive, negative and neutral.

Generally, in android we can build AlertDialog in our activity file using different dialog methods.

Android AlertDialog Methods


Following are the some of commonly used methods related to AlertDialog control to built alert
prompt in android applications.
 
Method Description

setTitle() It is used to set the title of alertdialog and its an optional component.

setIcon() It is used to set the icon before the title


Method Description

setMessage() It is used to set the message required message to display in alertdialog.

setCancelable() It is used to allow users to cancel alertdialog by clicking on outside of dialog


area by setting true / false.

setPositiveButton() It is used to set the positive button for alertdialog and we can implement
click event of positive button.

setNegativeButton( It is used to set the negative button for alertdialog and we can implement
) click event of negative button.

setNeutralButton() It is used to set the neutral button for alertdialog and we can implement click
event of neutral button.

Android AlertDialog Example

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
      <Button
        android:id="@+id/getBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="150dp"
        android:layout_marginTop="200dp"
        android:text="Show Alert" />
</RelativeLayout>
MainActivity.java
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = (Button)findViewById(R.id.getBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder
= new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Login Alert")
                        .setMessage("Are you sure, you want to
continue ?")
                        .setCancelable(false)
                       
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface
dialog, int which) {
                               
Toast.makeText(MainActivity.this,"Selected Option:
YES",Toast.LENGTH_SHORT).show();
                            }
                        })
   
.setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface
dialog, int which) {
                               
Toast.makeText(MainActivity.this,"Selected Option:
No",Toast.LENGTH_SHORT).show();
                            }
                        });
                //Creating dialog box
                AlertDialog dialog  = builder.create();
                dialog.show();
            }
        });
    }
}

Android AlertDialog Add Items List


There are three different kind of lists available with AlertDialogs in android, those are
 

 Single Choice List


 Single Choice List with Radio Buttons
 Single Choice List with Checkboxes

Android AlertDialog Setmultichoiceitems Example

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent" android:layout_height="match_pare
nt">
      <Button
        android:id="@+id/getBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="150dp"
        android:layout_marginTop="200dp"
        android:text="Show Alert" />
</RelativeLayout>

MainActivity.java
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    final CharSequence[] colors = { "Pink", "Red", "Yellow", "Blue" };
    ArrayList<Integer> slist = new ArrayList();
    boolean icount[] = new boolean[colors.length];
    String msg ="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = (Button)findViewById(R.id.getBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder
= new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Choose Colors")
                .setMultiChoiceItems(colors,icount, new DialogInterface.O
nMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface
arg0, int arg1, boolean arg2) {
                       if (arg2) {
                            // If user select a item then add it in
selected items
                           slist.add(arg1);
                        } else if (slist.contains(arg1)) {
                            // if the item is already selected then
remove it
                           slist.remove(Integer.valueOf(arg1));
                        }
                    }
                })      .setCancelable(false)
                       
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface
dialog, int which) {
                                msg = "";
                                for (int i = 0; i < slist.size(); i++) {
                                    msg = msg + "\n" + (i + 1) + " :
" + colors[slist.get(i)];
                                }
                               
Toast.makeText(getApplicationContext(), "Total " + slist.size() + " Items
Selected.\n" + msg, Toast.LENGTH_SHORT).show();
                            }
                        })
                       
.setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface
dialog, int which) {
                                Toast.makeText(MainActivity.this,"No
Option Selected",Toast.LENGTH_SHORT).show();
                            }
                        });
                //Creating dialog box
                AlertDialog dialog  = builder.create();
                dialog.show();
            }
        });
    }
}
Android Menus (Options, Context,
Popup)
In android, Menu is a part of user interface (UI) component which is used to handle some common
functionality around the application. By using Menus in our applications, we can provide better and
consistent user experience throughout the application.
 
We can use Menu APIs to represent user actions and other options in our android application
activities.
 
In android, we can define a Menu in separate XML file and use that file in
our activities or fragments based on our requirements.

Define a Android Menu in XML File


For all menu types, Android provides a standard XML format to define menu items. Instead of
building a menu in our activity's code, we should define a menu and all its items in an XML menu
resource and load menu resource as a Menu object in our activity or fragment.
 
In android, to define menu, we need to create a new folder menu inside of our project resource
directory (res/menu/) and add a new XML file to build the menu with the following elements.
 
Element Description

<menu> It’s a root element to define a Menu in XML file and it will hold one or more and
elements.

<item> It is used to create a menu item and it represent a single item in menu. This element
may contain a nested <menu> element in order to create a submenu.

<group It’s an optional and invisible for <item> elements. It is used to categorize the menu
> items so they share properties such as active state and visibility.

Following is the example of defining a menu in XML file (menu_example.xml).


 
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/mail"
        android:icon="@drawable/ic_mail"
        android:title="@string/mail" />
    <item android:id="@+id/upload"
        android:icon="@drawable/ic_upload"
        android:title="@string/upload"
        android:showAsAction="ifRoom" />
    <item android:id="@+id/share"
        android:icon="@drawable/ic_share"
        android:title="@string/share" />
</menu>
The <item> element in menu supports different type of attributes to define item’s behaviour and
appearance. Following are the some of commonly used <item> attributes in android applications.
 
Attribute Description

android:id It is used to uniquely identify element in application.

android:icon It is used to set the item's icon from drawable folder.

android:title It is used to set the item's title

android:showAsActio It is used to specify how the item should appear as an action item in the
n app bar.

In case if we want to add submenu in menu item, then we need to add a <menu> element as the


child of an <item>. Following is the example of defining a submenu in menu item.
 
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/file"
        android:title="@string/file" >
        <!-- "file" submenu -->
        <menu>
            <item android:id="@+id/create_new"
                android:title="@string/create_new" />
            <item android:id="@+id/open"
                android:title="@string/open" />
        </menu>
    </item>
</menu>
Load Android Menu from an Activity
Once we are done with creation of menu, we need to load the menu resource from
our activity using MenuInflater.inflate() like as shown below.
 
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_example, menu);
}
If you observe above code we are calling our menu using MenuInflater.inflate() method in the form
of R.menu.menu_file_name. Here our xml file name is menu_example.xml so we used file
name menu_example.

Handle Android Menu Click Events


In android, we can handle a menu item click events using ItemSelected() event based on the menu
type. Following is the example of handling a context menu item click event
using onContextItemSelected().
 
@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.mail:
            // do something
            return true;
        case R.id.share:
            // do something
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}
If you observe above code, the getItemId() method will get the id of selected menu item based on
that we can perform our actions.

Android Different Types of Menus


In android, we have a three fundamental type of Menus available to define a set of options and
actions in our android applications.
 
Following are the commonly used Menus in android applications.
 
 Options Menu
 Context Menu
 Popup Menu

Android Options Menu


In android, Options Menu is a primary collection of menu items for an activity and it is useful to
implement actions that have a global impact on the app, such as Settings, Search, etc.
 
To know more about Options Menu, check this Android Options Menu with Examples.

Android Context Menu


In android, Context Menu is a floating menu that appears when the user performs a long click on an
element and it is useful to implement an actions that effect the selected content or context frame.
 
To know more about Context Menu, check this Android Context Menu with Examples.

Android Popup Menu


In android, Popup Menu displays a list of items in a vertical list that’s anchored to the view that
invoked the menu and it’s useful for providing an overflow of actions that related to specific content.

Android Options Menu with


Examples

Android Fragments with Examples


In android, Fragments are the modular section of an activity design and these are used to represent
the behaviour of user interface (UI) in an activity. By using fragments we can create a flexible UI
designs that can be adjusted based on the device screen size such as tablets, smartphones.
 
We can build multi-pane UI by combining multiple fragments in a single activity and we can reuse
same fragment in multiple activities. The fragment has its own lifecycle call-backs and accept its own
input events.
 
We can add or remove fragments in an activity while activity is running. In android, the fragment will
act as a sub-activity and we can reuse it in multiple activities.
 
Generally, in android the fragment must be included in an activity due to that the fragment lifecycle
will always effected by the host activity life cycle. In case if we pause an activity, all the fragments
related to an activity will also be stopped.
 
In android, we can insert fragment into activity layout by using <fragment> element and by dividing
the layout of an activity into fragments, we can modify the appearance of an app design at runtime.
We can also implement a fragment without having any user interface (UI).
 
It’s an optional to use fragments into activity but by doing this it will improve the flexibility of our
app UI and make it easier to adjust our app design based on the device size.
 
Following is the example of defining a multiple fragments in single activity for the tablet design to
display the details of an item which we selected in app, but separated for mobile design.
 

 
If you observe above example for Tablet we defined an Activity A with two fragments such as one is
to show the list of items and second one is to show the details of item which we selected in first
fragment.
 
For Handset device, there is no enough space to show both the fragments in single activity, so
the Activity A includes first fragment to show the list of items and the Activity B which includes
another fragment to display the details of an item which is selected in Activity A.
 
For example, GMAIL app is designed with multiple fragments, so the design of GMAIL app will be
varied based on the size of device such as tablet or mobile device.
 
Table View
 

 
Mobile View
 
Android Fragment Life Cycle
Following is pictorial representation of android fragment life cycle while its activity is running.
 
 
Following are the list of methods which will perform during the lifecycle of fragment in android
applications.
 
Method Description

onAttach() It is called when the fragment has been associated with an activity.

onCreate() It is used to initialize the fragment.

onCreteView() It is used to create a view hierarchy associated with the fragment.

onActivityCreated( It is called when the fragment activity has been created and the fragment
) view hierarchy instantiated.

onStart() It is used to make the fragment visible.

onResume() It is used to make the fragment visible in an activity.

onPause() It is called when fragment is no longer visible and it indicates that the user is
leaving the fragment.

onStop() It is called to stop the fragment using onStop() method.

onDestoryView() The view hierarcy which associated with the fragment is being removed after
executing this method.

onDestroy() It is called to perform a final clean up of the fragments state.

onDetach() It is called immediately after the fragment disassociated from the activity.

Android Fragments Examples


Following is the example of creating a two fragments, two buttons and showing the respective
fragment when click on button in android application.
Create a new android application using android studio and give names as Fragments. In case if you
are not aware of creating an app in android studio check this article Android Hello World App.
 
Now we need to create our own custom fragment layout files (listitems_info.xml, details_info.xml)
in \res\layout path to display those fragments in main layout for that right click on your layout
folder  Go to New  select Layout resource file and give name as listitems_info.xml.
 
Once we create a new file listitems_info.xml, open it and write the code like as shown below

Listitems_info.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@android:id/list" />
</LinearLayout>

Same way create another file details_info.xml, open it and write the code like as shown below

details_info.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0079D6">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"
        android:layout_marginTop="200px"
        android:layout_marginLeft="200px"
        android:id="@+id/Name"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="200px"
        android:textColor="#ffffff"
        android:id="@+id/Location"/>
</LinearLayout>

Now we need to create our own custom fragment class files


(ListMenuFragment.java, DetailsFragment.java) in \java\com.tutlane.fragmentsexample path to
bind and display data in fragments for that right click on your application folder  Go to
New  select Java Class and give name as DetailsFragment.java.
 
Once we create a new file DetailsFragment.java, open it and write the code like as shown below

DetailsFragment.java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by tutlane on 06-08-2017.
 */

public class DetailsFragment extends Fragment {
    TextView name,location;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.details_info,
container, false);
        name = (TextView)view.findViewById(R.id.Name);
        location = (TextView)view.findViewById(R.id.Location);
        return view;
    }
    public void change(String uname, String ulocation){
        name.setText(uname);
        location.setText(ulocation);
    }
}

If you observe above code we extended class with Fragment and used LayoutInflater to show the
details of fragment. We defined a function change() to change the text in textview.
 
Same way create another file ListMenuFragment.java, open it and write the code like as shown
below

ListMenuFragment.java
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * Created by tutlane on 06-08-2017.
 */
public class ListMenuFragment extends ListFragment {
    String[] users = new String[]
{ "Suresh","Rohini","Trishika","Praveen","Sateesh","Madhav" };
    String[] location = new String[]
{"Hyderabad","Guntur","Hyderabad","Bangalore","Vizag","Nagpur"};
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.listitems_info,
container, false);
        ArrayAdapter<String> adapter
= new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, users);
        setListAdapter(adapter);
        return view;
    }
    @Override
    public void onListItemClick(ListView l, View
v, int position, long id) {
        DetailsFragment txt =
(DetailsFragment)getFragmentManager().findFragmentById(R.id.fragment2);
        txt.change("Name: "+ users[position],"Location :
"+ location[position]);
        getListView().setSelector(android.R.color.holo_blue_dark);
    }
}
If you observe above code we extended our class using ListFragment and we defined two array of
strings users, location which contains names and locations. We defined onListItemClick event to
update the name and location in DetailsFragment based on the list item which we clicked.
 
Now we need to display our fragments horizontally side by side in main layout for that
open activity_main.xml file and write code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.tutlane.fragmentsexample.MainActivity">

    <fragment
        android:layout_height="match_parent"
        android:layout_width="350px"
        class="com.tutlane.fragmentsexample.ListMenuFragment"
        android:id="@+id/fragment"/>
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.tutlane.fragmentsexample.DetailsFragment"
        android:id="@+id/fragment2"/>
</LinearLayout>

We are not going to make any modifications for our main activity file (MainActivity.java) and
manifest file (AndroidMainfest.xml).
Android Tabs with Fragments and
ViewPager
In android, we can create swipeable tabs layout using Swipe Views to switch between the tabs in
android application. The Swipe Views in android provides a navigation between the sibling screens
such as tabs with a horizontal finger gesture, sometimes it is called as horizontal paging.
 
By using android ViewPager widget, we can create Swipe Views in our android applications. In
android, ViewPager is a layout widget in which each child view is treated as a separate tab in the
layout.
 
To set up our tab layout with ViewPager, we need to add a <ViewPager> element in our XML
layout. For example, to make each child view in the swipe view to consume entire tab layout, our
layout should be like as shown following.
 

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

To insert child views that represent each page, we need to add this layout to PagerAdapter. There
are two kinds of adapters that we can use it in our android application.
 
Adapter Description

FragmentPagerAdapter This adapter is best, when we are navigating between sibling screens
which representing a fixed, small number of pages.

FragmentStatePagerAdapte This is best for paging across a collection of objects for which the
r number of pages is undetermined. It destroys fragments as the user
navigates to other pages, minimizing memory usage.

Now we will see how to create a tab layout with swipe views for switching between the tabs
using ViewPager and Fragments in android application like as shown following.
Android Tabs Layout Example
Following is the example of creating a tabs layout with swipe views for switching between the tabs
using material design in android application.
 
Create a new android application using android studio and give names as TabsExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.
 
To start creating the tabs layout in our android application, we need to add following libraries in
dependencies section of build.gradle file in Module section like as shown below.
 
dependencies {
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
}Here we are going to show the tabs using android ToolBar and TabLayout so we need to remove
the actionbar from layout using styles, for that open styles.xml file from /res/values folder and that
should contain the code like as shown below. 

styles.xml
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
</resources>

Android WebView with Examples


In android, WebView is an extension of View class and it is used to show the static HTML web pages
content or remote web pages content with URL in android applications as a part of our activity
layout.
 
Generally, in android the WebView will act as an embedded browser to include the web pages
content in our activity layout and it won’t contain any features of normal browser, such as address
bar, navigation controls, etc.
 
Following is the pictorial representation of WebView in android applications.
 

 
Generally, in android WebView is useful to include and show the content of other web pages or
application content in our required pages, such as an end-user agreements, etc.

Android WebView Example


Following is the example of showing a static HTML content in WebView in android applications.
 
Create a new android application using android studio and give names as WebView. In case if you
are not aware of creating an app in android studio check this article Android Hello World App.
 
Now open an activity_main.xml file from /res/layout path and write the code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

Once we are done with adding a WebView to the layout, now we will show the static HTML content
in WebView, for that open main activity
file MainActivity.java from \java\com.tutlane.webview path and write the code like as shown
below.

MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView wv = (WebView) findViewById(R.id.webview);
        String customHtml = "<html><body><h1>Welcome to Tutlane</h1>" +
                "<h2>Welcome to Tutlane</h2><h3>Welcome to
Tutlane</h3>" +
                "<p>It's a Static Web HTML Content.</p>" +
                "</body></html>";
        wv.loadData(customHtml, "text/html", "UTF-8");
    }
}

If you observe above code, we are calling our layout using setContentView method in the form
of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file
name activity_main and trying to show the static HTML content in WebView.
 
Generally, during the launch of our activity, onCreate() callback method will be called by android
framework to get the required layout for an activity.

Android Show Web URL Content in WebView Example


Generally, in android WebView will act as an embedded browser to show the static or remote web
page content in our android applications.
 
Now we will see how to load remote URL content in WebView with example in android application. 
 
By using WebView LoadURL property we can load remote URL content in our android applications.
To show the remote URL content in webview modify MainActivity.java file code like as shown
below.

ManiActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://tutlane.com");
    }
}

If you observe above example, we are trying to load the remote URL (http://tutlane.com) content in
our android application using WebView and we set a property setJavaScriptEnabled() to enable
JavaScript because by default the JavaScript is disabled in WebView.
 
Generally, the web page which we are loading in WebView might use JavaScript. In case if we won’t
enable the JavaScript, the functionality which related to JavaScript in web page won’t work that’s the
reason we are enabling the JavaScript using setJavaScriptEnabled() 
 
To load the remote web URL content, our application must have an access to the internet. We need
to set the internet access permissions like as shown below.

<manifest ……>
……
    <uses-permission android:name="android.permission.INTERNET" />
……
</manifest>

Android Navigation Drawer Sliding


Menu
In android, Navigation Drawer is a panel that displays the app main navigation options on the left
edge of the screen like sliding menu. The navigation drawer is hidden most of the time, but it is
revealed when the user swipes a finger from the left edge of the screen or, while at the top level of
the app, the user touches the app icon in the action bar.
 
The Navigation Drawer slides in from the left and contains the navigation destinations for our app.
While creating the android application if we select Navigation Drawer Activity, automatically the
navigation drawer menu will be created with all required sliding menu options.
 
Now we will see how to create navigation drawer sliding menu using Navigation Drawer Activity in
android application with example.

Android Navigation Drawer Example


Following is the example of creating navigation drawer sliding menu in android application.
 
Create a new android application using android studio and give names
as NavigationDrawerExample like as shown below.
 

 
Now we need to select the form factors which we need for our app. In case if you're not sure what
you need, just select Phone and Tablet and then click Next like as shown below.
 
 
Now select the Navigation Drawer Activity in 'Add an activity to Mobile' dialog and
click Next like as shown below.
 
 
Customize the activity by entering activity name, layout name and title as prompted. In case if default
values are fine, then click Finish like as shown below.
 
 
Once project created, automatically all the required details will be added in project to create the
navigation drawer sliding menu like as shown below.
 
 
If you observe above project structure, android studio automatically created all the required files to
create navigation drawer sliding menu.
 
Now open activity_main.xml file from \res\layout folder path and it will contain the code like as
shown below.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.and
roid.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>

Now open your main activity

MainActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton)
findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is
present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {
        } else if (id == R.id.nav_slideshow) {
        } else if (id == R.id.nav_manage) {
        } else if (id == R.id.nav_share) {
        } else if (id == R.id.nav_send) {
        }
        DrawerLayout drawer = (DrawerLayout)
findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Android Camera App with Examples


In android, Camera is useful to capture the photos and videos in our applications. By using camera
api we can control the functionalities of camera based on our requirements.
 
The android framework provides a two ways such as android.hardware.camera2 api and
camera intent to capture the images and videos in our application.

android.hardware.camera2
It’s a primary API for controlling the device cameras. By using this we can take the pictures or videos
from our application using camera.

Intent
By using intent action types
either MediaStore.ACTION_IMAGE_CAPTURE or MediaStore.ACTION_VIDEO_CAPTURE, we can
capture the photos or videos without directly using the Camera object.
 
The best way is to use an Intent to invoke an existing Android camera application to take pictures or
videos in our application without writing a lot of extra code.
 
In android, By using startActivityForResult() method with intent action
parameter MediaStore.ACTION_IMAGE_CAPTURE, we can take the pictures from our android
applications.
 
Following is the code snippet to capture the pictures using intent object with action
parameter MediaStore.ACTION_IMAGE_CAPTURE in android applications.
 
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);

If you observe above code snippet, we used startActivityForResult() method


with MediaStore.ACTION_IMAGE_CAPTURE intent action parameter to capture the photos. The
second parameter Image_Capture_Code is a locally defined integer that must be greater than 0.

Android Camera App Example


Following is the example of using an existing camera app in our android applications to capture the
photos on button click.
 
Create a new android application using android studio and give names as CameraExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.
 
Once we create an application, open activity_main.xml file from \res\layout folder path and write
the code like as shown below.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">
    <Button
        android:id="@+id/btnTakePicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Take a Photo"
        android:textStyle="bold"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true" />
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/capturedImage"
        android:layout_above="@+id/btnTakePicture"/>
</RelativeLayout>
Now open your main activity file MainActivity.java from \java\com.tutlane.cameraexample path
and write the code like as shown below

MainActivity.java
package com.tutlane.cameraexample;
import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button btnCapture;
    private ImageView imgCapture;
    private static final int Image_Capture_Code = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCapture =(Button)findViewById(R.id.btnTakePicture);
        imgCapture = (ImageView) findViewById(R.id.capturedImage);
        btnCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent cInt
= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cInt,Image_Capture_Code);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
        if (requestCode == Image_Capture_Code) {
            if (resultCode == RESULT_OK) {
                Bitmap bp = (Bitmap) data.getExtras().get("data");
                imgCapture.setImageBitmap(bp);
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "Cancelled",
Toast.LENGTH_LONG).show();
            }
        }
    }
}

If you observe above code snippet, we used startActivityForResult() method


with MediaStore.ACTION_IMAGE_CAPTURE intent action parameter to capture the photos.

Android Audio / Media Player with


Examples
In android, by using MediaPlayer class we can easily fetch, decode and play both audio and video
files with minimal setup.
 
The android media framework provides a built in support for playing a variety of common media
types, such as audio or video. We have a multiple ways to play audio or video but the most
important component of media framework is MediaPlayer class.

Android MediaPlayer Class


In android, by using MediaPlayer class we can access audio or video files from application (raw)
resources, standalone files in file system or from a data stream arriving over a network connection
and play audio or video files with the multiple playback options such as play, pause, forward,
backward, etc.
 
Following is the code snippet, to play an audio that is available in our application’s local raw resource
(res/raw) directory.
 
MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.baitikochi_chuste);
mPlayer.start();
The second parameter in create() method is the name of the song that we want to play from our
application resource directory (res/raw). In case if raw folder not exists in your application, create a
new raw folder under res directory and add a properly encoded and formatted media files in it.
 
In case, if we want to play an audio from a URI that is locally available in the system, we need to
write the code like as shown below.
 
Uri myUri = ....; // initialize Uri here
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(getApplicationContext(), myUri);
mPlayer.prepare();
mPlayer.start();

If we want to play an audio from a URL via HTTP streaming, we need to write the code like as shown
below.
 
String url = "http://........"; // your URL here
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(url);
mPlayer.prepare(); // might take long! (for buffering, etc)
mPlayer.start();

If you observe above code snippets, we create an instance of MediaPlayer class and added required
audio source, streaming type, audio file path, etc. to play an audio from our application.
 
Apart from above methods, MediaPlayer class provides a different type of methods to control audio
and video files based on requirements.
 
Method Description

getCurrentPosition() It is used to get the current position of song in milliseconds.

getDuration() It is used to get the total time duration of song in milliseconds.

isPlaying() It returns true / false to indicate whether song playing or not.

pause() It is used to pause the song playing.


Method Description

setAudioStreamType( it is used to specify the audio streaming type.


)

setDataSource() It is used to specify the path of audio / video file to play.

setVolume() It is used to adjust media player volume either up / down.

seekTo(position) It is used to move song to particular position in milliseconds.

getTrackInfo() It returns an array of track information.

start() It is used to start playing the audio / video.

stop() It is used to stop playing the audio / video.

reset() It is used to reset the MediaPlayer object.

release() It is used to releases the resources which are associated with MediaPlayer
object.

Now we will see how to implement media playing application using MediaPlayer to play a song or
audio with multiple playback options, such as play, pause, forward, backward in android application
with examples.

Android Audio Player Example


Following is the example of implementing an audio player to play a song or audio with multiple
playback options using MediaPlayer.
 
Create a new android application using android studio and give names as MediaPlayerExample. In
case if you are not aware of creating an app in android studio check this article Android Hello World
App.
 
As discussed create a new raw folder in res directory and add one music file like as shown below to
play it by using MediaPlayer class.
 

 
Now open activity_main.xml file from \res\layout folder path and write the code like as shown
below.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">
    <TextView
        android:id="@+id/txtVw1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Now Playing: "
        android:layout_marginTop="30dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <TextView
        android:id="@+id/txtSname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/txtVw1"
        android:layout_toRightOf="@+id/txtVw1"
        android:text="TextView" />
    <ImageView
        android:id="@+id/imgLogo"
        android:layout_width="match_parent"
        android:layout_height="450dp"
        android:layout_below="@+id/txtVw1"
        android:src="@drawable/tutlane" />
    <ImageButton
        android:id="@+id/btnBackward"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="44dp"
        android:layout_marginLeft="20dp"
        android:src="@android:drawable/ic_media_rew" />
    <ImageButton
        android:id="@+id/btnPlay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/btnBackward"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/btnBackward"
        android:src="@android:drawable/ic_media_play" />
    <ImageButton
        android:id="@+id/btnPause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/btnPlay"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/btnPlay"
        android:src="@android:drawable/ic_media_pause" />
    <ImageButton
        android:id="@+id/btnForward"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/btnPause"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/btnPause"
        android:contentDescription="@+id/imageButton3"
        android:src="@android:drawable/ic_media_ff" />
      <TextView
        android:id="@+id/txtStartTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/sBar"
        android:text="0 min, 0 sec" />
    <SeekBar
        android:id="@+id/sBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnBackward"
        android:layout_toLeftOf="@+id/txtSongTime"
        android:layout_toRightOf="@+id/txtStartTime" />
    <TextView
        android:id="@+id/txtSongTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/btnForward"
        android:layout_alignTop="@+id/sBar"
        android:text="0 min, 0 sec " />
</RelativeLayout>
Now open your main activity
file MainActivity.java from \java\com.tutlane.audioplayerexample path and write the code like as
shown below.

MainActivity.java
package com.tutlane.mediaplayerexample;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    private ImageButton forwardbtn, backwardbtn, pausebtn, playbtn;
    private MediaPlayer mPlayer;
    private TextView songName, startTime, songTime;
    private SeekBar songPrgs;
    private static
int oTime =0, sTime =0, eTime =0, fTime = 5000, bTime = 5000;
    private Handler hdlr = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        backwardbtn = (ImageButton)findViewById(R.id.btnBackward);
        forwardbtn = (ImageButton)findViewById(R.id.btnForward);
        playbtn = (ImageButton)findViewById(R.id.btnPlay);
        pausebtn = (ImageButton)findViewById(R.id.btnPause);
        songName = (TextView)findViewById(R.id.txtSname);
        startTime = (TextView)findViewById(R.id.txtStartTime);
        songTime = (TextView)findViewById(R.id.txtSongTime);
        songName.setText("Baitikochi Chuste");
        mPlayer = MediaPlayer.create(this, R.raw.baitikochi_chuste);
        songPrgs = (SeekBar)findViewById(R.id.sBar);
        songPrgs.setClickable(false);
        pausebtn.setEnabled(false);

        playbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Playing Audio",
Toast.LENGTH_SHORT).show();
                mPlayer.start();
                eTime = mPlayer.getDuration();
                sTime = mPlayer.getCurrentPosition();
                if(oTime == 0){
                    songPrgs.setMax(eTime);
                    oTime =1;
                }
                songTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(eTime),
                        TimeUnit.MILLISECONDS.toSeconds(eTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(eTime))) );
                startTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(sTime),
                        TimeUnit.MILLISECONDS.toSeconds(sTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(sTime))) );
                songPrgs.setProgress(sTime);
                hdlr.postDelayed(UpdateSongTime, 100);
                pausebtn.setEnabled(true);
                playbtn.setEnabled(false);
            }
        });
        pausebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayer.pause();
                pausebtn.setEnabled(false);
                playbtn.setEnabled(true);
                Toast.makeText(getApplicationContext(),"Pausing Audio",
Toast.LENGTH_SHORT).show();
            }
        });
        forwardbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if((sTime + fTime) <= eTime)
                {
                    sTime = sTime + fTime;
                    mPlayer.seekTo(sTime);
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Cannot jump
forward 5 seconds", Toast.LENGTH_SHORT).show();
                }
                if(!playbtn.isEnabled()){
                    playbtn.setEnabled(true);
                }
            }
        });
        backwardbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if((sTime - bTime) > 0)
                {
                    sTime = sTime - bTime;
                    mPlayer.seekTo(sTime);
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Cannot jump
backward 5 seconds", Toast.LENGTH_SHORT).show();
                }
                if(!playbtn.isEnabled()){
                    playbtn.setEnabled(true);
                }
            }
        });
    }
    private Runnable UpdateSongTime = new Runnable() {
        @Override
        public void run() {
            sTime = mPlayer.getCurrentPosition();
            startTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(sTime),
                    TimeUnit.MILLISECONDS.toSeconds(sTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(sTime))) );
            songPrgs.setProgress(sTime);
            hdlr.postDelayed(this, 100);
        }
    };
}
If you observe above code we used MeidaPlayer object properties to play, pause song and
changing the song position either forward or backward based on our requirements.
Android Video Player with Examples
In android, by using VideoView component and MediaController class we can easily implement the
video player in android applications to play the videos with multiple playback options, such as play,
pause, forward, backward, etc.
 
Generally, the MediaController class in android will provide a playback options for video player,
such as play, pause, backward, forward, etc.
 
The VideoView class in android will provide a functionalities to fetch and play the videos using video
player with minimal setup in android applications.
 
Following is the code snippet, to use VideoView and MediaController classes to implement video
player in android application to play videos based on our requirements.
 
VideoView videoView =(VideoView)findViewById(R.id.vdVw);
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" +
R.raw.video1);
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
If you observe above code snippet, we created an instance of MediaController, VideView class and
added required video source and add playback options to video player by using VideoView object.
 
Here we used Uri object to play videos from our application resource directory (res/raw). In case
if raw folder not exists in our application, create a new raw folder under res directory and add a
properly encoded and formatted video files in it.
 
Apart from above methods, VideoView class provides a different type of methods to control video
files based on requirements.
 
Method Description

setMediaController() It is used to set the media controller to videoview.

setVideoURI() It is used to set the path of video file.

pause() It is used to pause the video playing.


Method Description

stopPlayback() it is used to stop the video playing.

seekTo(position) It is used to move video to particular position in milliseconds.

resume() It is used to resume the video playing.

start() It is used to start playing the audio / video.

stopPlayback() It is used to stop playing the audio / video.

Now we will see how to implement video playing application


using MediaController and VideoView with multiple playback options, such as play, pause, forward,
backward in android application with examples.

Android Video Player Example


Following is the example of implementing a video player to play video with multiple playback
options using VideoView and MediaController objects.
 
Create a new android application using android studio and give names as VideoPlayerExample. In
case if you are not aware of creating an app in android studio check this article Android Hello World
App.
 
As discussed create a new raw folder in res directory and add one video file like as shown below.
 
 
Now open activity_main.xml file from \res\layout folder path and write the code like as shown
below.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android
"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">
    <VideoView
        android:id="@+id/vdVw"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center" />
</RelativeLayout>
Now open your main activity
file MainActivity.java from \java\com.tutlane.videoplayerexample path and write the code like as
shown below

MainActivity.java
package com.tutlane.videoplayerexample;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        VideoView videoView =(VideoView)findViewById(R.id.vdVw);
        //Set MediaController  to enable play, pause, forward, etc
options.
        MediaController mediaController= new MediaController(this);
        mediaController.setAnchorView(videoView);
        //Location of Media File
        Uri uri = Uri.parse("android.resource://" + getPackageName()
+ "/" + R.raw.video1);
        //Starting VideView By Setting MediaController and URI
        videoView.setMediaController(mediaController);
        videoView.setVideoURI(uri);
        videoView.requestFocus();
        videoView.start();
    }
}
If you observe above code we used MediaController and VideoView objects with required
properties to implement video player based on our requirements. 

Android GridView with Examples


In android, Grid View is a ViewGroup which is used to display items in a two dimensional, scrollable
grid and grid items are automatically inserted to the gridview layout using a list adapter.
 
Generally, the adapter pulls data from a sources such as an array or database and converts each item
into a result view and that’s placed into the list.
 
Following is the pictorial representation of GridView in android applications.
 
Android Adapter
In android, Adapter will act as an intermediate between the data sources and adapter views such
as ListView, Gridview to fill the data into adapter views. The adapter will hold the data and iterates
through an items in data set and generate the views for each item in the list.
 
Generally, in android we have a different types of adapters available to fetch the data from different
data sources to fill the data into adapter views, those are
 
Adapter Description

ArrayAdapter It will expects an Array or List as input.

CurosrAdapter It will accepts an instance of cursor as an input.

SimpleAdapte It will accepts a static data defined in the resources.


r

BaseAdapter It is a generic implementation for all three adapter types and it can be used
for ListView, Gridview or Spinners based on our requirements
Android GridView Example
Following is the simple example showing user details using GridView and showing the position of
particular image when clicking on it in android applications.
 
Create a new android application using android studio and give names as GridView. In case if you
are not aware of creating an app in android studio check this article Android Hello World App.
 
Once we create an application, add some sample images to project /res/drawable directory to show
the images in GridView.
 
Now open an activity_main.xml file from /res/layout path and write the code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="110dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center" />
Once we are done with creation of layout, we need to create a custom adapter (ImageAdapter.java)
by extending it using BaseExtender to show all the items in the grid, for that right click
on java folder  Give name as ImageAdapter.java and click OK.
 
Open ImageAdapter.java file and write the code like as shown below

ImageAdapter.java
package com.tutlane.gridview;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
/**
 * Created by tutlane on 24-08-2017.
 */
public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    public ImageAdapter(Context c) {
        mContext = c;
    }
    public int getCount() {
        return thumbImages.length;
    }
    public Object getItem(int position) {
        return null;
    }
    public long getItemId(int position) {
        return 0;
    }
    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent)
{
            ImageView imageView = new ImageView(mContext);
           
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
            imageView.setImageResource(thumbImages[position]);
            return imageView;
    }
    // Add all our images to arraylist
    public Integer[] thumbImages = {
            R.drawable.img1, R.drawable.img2,
            R.drawable.img3, R.drawable.img4,
            R.drawable.img5, R.drawable.img6,
            R.drawable.img7, R.drawable.img8,
            R.drawable.img1, R.drawable.img2,
            R.drawable.img3, R.drawable.img4,
            R.drawable.img5, R.drawable.img6,
            R.drawable.img7, R.drawable.img8,
            R.drawable.img1, R.drawable.img2,
            R.drawable.img3, R.drawable.img4,
            R.drawable.img5
    };
}
If you observe above code we referred some images, actually those are the sample images which we
added in /res/drawable directory.
 
Now we will bind images to our GridView using our custom adapter (ImageAdapter.java), for that
open main activity file MainActivity.java from \java\com.tutlane.gridview path and write the code
like as shown below.
MainActivity.java
package com.tutlane.gridview
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridView gv = (GridView) findViewById(R.id.gvDetails);
        gv.setAdapter(new ImageAdapter(this));
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View
v, int position, long id) {
                Toast.makeText(MainActivity.this, "Image Position: " +
position, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
If you observe above code, we are binding image details to GridView using our custom adapter
(ImageAdapter.java) and calling our layout using setContentView method in the form
of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file
name activity_main.
 
Generally, during the launch of our activity, onCreate() callback method will be called by android
framework to get the required layout for an activity.

Output of Android GridView Example


When we run above example using android virtual device (AVD) we will get a result like as shown
below.
 
 
This is how we can bind images to GridView using Adapter in android applications based on our
requirements.

Android GridView Details Activity Example


In above example, we implemented an image gallery using gridview in android application. Now we
will extend the functionality of above example to show the selected grid image in full screen.
 
Now we need to create a new layout (image_details.xml) file in project /res/layout directory to
show the image details, for that right click on layouts folder  select New  Layout resource
file  Give name as image_details.xml and click OK. Now open newly created file
(image_details.xml) and write the code like as shown below.

image_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView android:id="@+id/full_image_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
Now we need to create a custom activity (FullImageActivity.java) to show the image details in our
newly created layout (image_details.xml) file, for that right click on java folder  select New  Java
Class  Give name as FullImageActivity.java and click OK.
 
Open FullImageActivity.java file and write the code like as shown below

FullImageActivity.java
package com.tutlane.gridview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;

/**
 * Created by tutlane on 24-08-2017.
 */
public class FullImageActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_details);
        // Get intent data
        Intent i = getIntent();
        // Get Selected Image Id
        int position = i.getExtras().getInt("id");
        ImageAdapter imageAdapter = new ImageAdapter(this);
        ImageView imageView = (ImageView)
findViewById(R.id.full_image_view);
        imageView.setImageResource(imageAdapter.thumbImages[position]);
    }
}
Now we need to include our newly created activity file (FullImageActivity.java)
in AndroidManifest.xml file like as shown below. For that, open AndroidManifest.xml file and
write the code like as shown below

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutlane.gridview">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
               
<category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- FullImageActivity -->
        <activity android:name=".FullImageActivity"></activity>
    </application>
</manifest>
Now we need to modify gridview image click function in main activity file (MainActivity.java) to get
image details and show it in new activity.
 
Open main activity file (MainActivity.java) and write the code like as shown below.

MainActivity.java
package com.tutlane.gridview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridView gv = (GridView) findViewById(R.id.gvDetails);
        gv.setAdapter(new ImageAdapter(this));
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View
v, int position, long id) {
                // Sending image id to FullScreenActivity
                Intent i = new Intent(getApplicationContext(),
FullImageActivity.class);
                // passing array index
                i.putExtra("id", position);
                startActivity(i);
            }
        });
    }
}
If you observe above code, we are getting the selected image details on image click and sending
those details to our newly created activity file to show the image in full screen.

Android ScrollView (Horizontal,


Vertical) with Examples
In android, ScrollView is a kind of layout which is useful to add a vertical or horizontal scroll bars to
the content which is larger than actual size of layouts such
as linearlayout, relativelayout, framelayout, etc.
 
Generally, the android ScrollView is useful when we have a content that doesn’t fit to our android
app layout screen. The ScrollView will enable a scroll to the content which is exceeding the screen
layout and allow users to see the complete content by scrolling.
 
The android ScrollView can hold only one direct child. In case, if we want to add multiple views
within the scroll view, then we need to include them in another standard layout
like linearlayout, relativelayout, framelayout, etc.
 
To enable scrolling for our android applications, ScrollView is the best option but we should not use
ScrollView along with ListView or Gridview because they both will take care of their own vertical
scrolling.
 
In android, ScrollView supports only vertical scrolling. In case, if we want to
implement horizontal scrolling, then we need to use HorizontalScrollView component.
 
The android ScrollView is having property called android:fillViewport, which is used to define
whether the ScrollView should stretch it’s content to fill the viewport or not.
 
Now we will see how to use ScrollView with linearlayout to enable scroll view to the content which is
larger than screen layout in android application with examples.

Android ScrollView Example


Following is the example of enabling vertical scrolling to the content which is larger than layout
screen using android ScrollView object.
 
Create a new android application using android studio and give names as ScrollViewExample. In
case if you are not aware of creating an app in android studio check this article Android Hello World
App.
 
Once we create an application, open activity_main.xml file from \res\layout folder path and write
the code like as shown below.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="false">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView android:id="@+id/loginscrn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:text="ScrollView"
        android:textSize="25dp"
        android:textStyle="bold"
        android:layout_gravity="center"/>
    <TextView android:id="@+id/fstTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Welcome to Tutlane"
        android:layout_gravity="center"/>
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        android:text="Button One" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        android:text="Button Two" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        android:text="Button Three" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        android:text="Button Four" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        android:text="Button Five" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        android:text="Button Six" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        android:text="Button Seven" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        android:text="Button Eight" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        android:text="Button Nine" />
</LinearLayout>
</ScrollView>

If you observe above code, we used a ScrollView to enable the scrolling for linearlayout whenever
the content exceeds layout screen.

If you observe above result, ScrollView provided a vertical scrolling for linearlayout whenever the


content exceeds layout screen.
 
As we discussed, ScrollView can provide only vertical scrolling for the layout. In case, if we want to
enable horizontal scrolling, then we need to use HorizontalScrollView in our application.
 
We will see how to enable horizontal scrolling for the content which is exceeding the layout screen in
android application.

Android HorizontalScrollView Example


Now open activity_main.xml file in your android application and write the code like as shown
below.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/a
ndroid"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="150dp">
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button One" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Two" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Three" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Four" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Five" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Six" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Seven" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Eight" />
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Nine" />
</LinearLayout>
</HorizontalScrollView>

If you observe above code, we used a HorizontalScrollView to enable horizontal scrolling


for linearlayout whenever the content exceeds layout screen.

Android TextToSpeech with


Examples
In android, by using TextToSpeech class we can easily convert our text into voice and it supports
different type speaking languages. We can choose the speaking language based on our
requirements in android application.
 
Generally, the android TextToSpeech instance can only be used to synthesize text once it has
completed its initialization so implement TextToSpeech.OnInitListener to notify the completion of
initialization.
 
During the initialization, we can set the audio pitch rate, audio speed, type of language to speak, etc.
based on our requirements

Following is the code snippet of converting text to voice using TextToSpeech class in android
applications.
 
public
class MainActivity extends AppCompatActivity implements TextToSpeech.OnIn
itListener {
    ....
   TextToSpeech textToSpeech;
    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            int result = textToSpeech.setLanguage(Locale.US);
String text = speakText.getText().toString();
            textToSpeech.speak(text,
TextToSpeech.QUEUE_FLUSH, null, null);
        }
    }
    ....
}
If you observe above code, we used TextToSpeech.OnInitListener to notify the completion of
initialization and used TextToSpeech class to convert entered text to voice.
 
Now we will see how to use TextToSpeech component to convert the given text to speech
conversion in android application with examples.

Android TextToSpeech Example


Following is the example of converting the given text to voice using android TextToSpeech object.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/fstTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="150dp"
        android:text="Enter Text to Speak"/>
    <EditText
        android:id="@+id/txtSpeak"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:ems="10"/>
    <Button
        android:id="@+id/btnSpeech"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:text="Speak" />
</LinearLayout>
Now open your main activity
file MainActivity.java from \java\com.tutlane.textspeechexample path and write the code like as
shown below
MainActivity.java
package com.tutlane.textspeechexample;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;

public
class MainActivity extends AppCompatActivity implements TextToSpeech.OnIn
itListener {
    Button speakBtn;
    EditText speakText;
    TextToSpeech textToSpeech;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        speakText = (EditText) findViewById(R.id.txtSpeak);
        speakBtn = (Button)findViewById(R.id.btnSpeech);
        textToSpeech = new TextToSpeech(this, this);
        speakBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                texttoSpeak();
            }
        });
    }
    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            int result = textToSpeech.setLanguage(Locale.US);
            if (result == TextToSpeech.LANG_MISSING_DATA || result ==
TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("error", "This Language is not supported");
            } else {
                texttoSpeak();
            }
        } else {
            Log.e("error", "Failed to Initialize");
        }
    }
    @Override
    public void onDestroy() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        super.onDestroy();
    }
    private void texttoSpeak() {
        String text = speakText.getText().toString();
        if ("".equals(text)) {
            text = "Please enter some text to speak.";
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                textToSpeech.speak(text,
TextToSpeech.QUEUE_FLUSH, null, null);
        }
        else {
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
    }
}
If you observe above code, we are converting the text to speech conversion
using TextToSpeech class.

Android Speech To Text


Step 1: Starting RecognizerIntent
First we need to create a RecognizerIntent by setting necessary flags such as
ACTION_RECOGNIZE_SPEECH – Simply takes user’s speech input and returns it to
same activity
LANGUAGE_MODEL_FREE_FORM – Considers input in free form English
EXTRA_PROMPT – Text prompt to show to the user when asking them to speak
Step 2: Receiving the speech response
Once the speech input is done we have to catch the response in onActivityResult and take
appropriate action needed.

Enabling Offline Mode


Right now all the devices are not supporting offline speech input. However you can follow
this discussion to enable offline speech input for supported devices.
I have downloaded speech input packages on my Nexus 5 and offline speech is working
fine.
1. On your device go to Settings -> Language and Input. Click on icon on Google voice input.
2. Under ALL tab select the language you want to download.
3. Once the language package downloaded, you can see it under INSTALLED tab.

Android Bluetooth 
In android, Bluetooth is a communication network protocol, which allow a devices to connect
wirelessly to exchange the data with other Bluetooth devices.
 
Generally, in android applications by using Bluetooth API’s we can implement Bluetooth
functionalities, such as searching for the available Bluetooth devices, connecting with the devices and
managing the data transfer between devices within the range.
 
By using android Bluetooth API’s in android applications, we can perform following functionalities.
 

 Scan for the available Bluetooth devices within the range


 Use local Bluetooth adapter for paired Bluetooth devices
 Connect to other devices through service discovery
 Transfer data to and from other devices
 Manage multiple connections

To transfer the data between two Bluetooth devices, first they must establish a communication
channel using pairing process. The devices which we are going to pair must be discoverable and
should accept the incoming connection requests. Generally, the devices will find the discoverable
devices using a service discovery process. Once the device accepts the pairing request, the two
devices will exchange a security keys to complete the bonding process and the devices will cache
these security keys for later use.
 
Once the pairing and bonding process completes, the devices are ready to exchange the required
information. When the session is complete, the device that initiated the pairing request will release
the channel that linked to the discoverable device. The two devices remain bonded, so they can
reconnect automatically during a future session as long as they're in the range of each other.

Android Set Bluetooth Permissions


To use Bluetooth features in our android applications, we must need to add multiple permissions,
such as BLUETOOTH and ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION in our
manifest file.
 
Permission Description

BLUETOOT We need this permission to perform any Bluetooth communication, such as


H requesting a connection, accepting a connection, and transferring data.

LOCATION We need this permission because the Bluetooth scans can be used to gather the
information about the location of user.

In case, if we want to discover the available Bluetooth devices or manipulate Bluetooth settings from
our app, we need to define BLUETOOTH_ADMIN permission.
 
Following is the example of defining the Bluetooth permissions in android manifest file.
 
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission androi
d:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>

Android BluetoothAdapter Class


In android, we can perform Bluetooth related activities by using BluetoothAdapter class in our
applications.
 
By using BluetoothAdapter object, we can interact with device’s Bluetooth adapter to perform
Bluetooth related operations. In case, if device does not contain any Bluetooth adapter, then it will
return null.
 
Following is the code snippet to initialize BluetoothAdapter class and to know whether the
Bluetooth is supported on the device or not.
 
BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
if(bAdapter==null)
{
    // Device won't support Bluetooth
}

If you observe above code snippet, we used getDefaultAdapter() method


of BluetoothAdapter class, which will return whether the device contains Bluetooth adapter or not.
 
In case if getDefaultAdapter() method returns NULL, then the device does not support Bluetooth
and we can disable all Bluetooth features.

Android Enable or Disable Bluetooth


If Bluetooth is supported but disabled, then isEnabled() method will return false and we can request
user to enable Bluetooth without leaving our application by using startActivityForResult() method
with ACTION_REQUEST_ENABLE intent action parameter.
 
Following is the code snippet to enable a Bluetooth by
using BluetoothAdapter parameter ACTION_REQUEST_ENABLE.
 
if(!bAdapter.isEnabled())
{
    Intent eintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(eintent, intVal);
}
If you observe above code snippet, we used startActivityForResult() method
with ACTION_REQUEST_ENABLE  intent action parameter to enable a Bluetooth.
 
The second parameter intVal in startActivityForResult() method is a locally defined integer that
must be greater than 0 and the system will return this parameter back to us
during onActivityResult() implementation as a requestCode parameter.
 
To know more about to TURN ON / OFF Bluetooth in android applications, check this Android
Bluetooth Turn ON / OFF with Examples.

Android Enable Discoverability


To make the device discoverable to other devices, we need to start the new activity by
calling startActivityForResult(intent, int) with the ACTION_REQUEST_DISCOVERABLE intent.
 
Following is the code snippet to enable the system’s discoverable mode to make sure that the device
discoverable to other devices.
 
Intent dIntent
=  new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(dIntent);

If you observe above code snippet, we are making sure our device discoverable to other devices
using ACTION_REQUEST_DISCOVERABLE. By default, the device becomes discoverable for 120
seconds. We can extend the device discoverable duration up to 3600 seconds (1 hour), by adding
the EXTRA_DISCOVERABLE_DURATION extra.
 
To know more about device discoverability, check this Android Bluetooth Device Discoverability with
Examples.

Android List Paired Devices


By using BluetoothAdapter method getBondedDevices(), we can get the Bluetooth paired devices
list.
 
Following is the code snippet to get all paired devices with name and MAC address of each device.
 
// Get paired devices.
Set<BluetoothDevice> pairedDevices = bAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
    // There are paired devices. Get the name and address of each paired
device.
    for (BluetoothDevice device : pairedDevices) {
        String deviceName = device.getName();
        String deviceHardwareAddress = device.getAddress(); // MAC
address
    }
}

If you observe above code, we are getting the Bluetooth paired devices name and mac address by
using BluetoothDevice object.

RecyclerView
In Android, RecyclerView is an advanced and flexible version of ListView and GridView. It
is a container used for displaying large amount of data sets that can be scrolled very
efficiently by maintaining a limited number of views. RecyclerView was introduced in
Material Design in API level 21 (Android 5.0 i.e Lollipop).
In Android, RecyclerView provides an ability to implement the horizontal, vertical and
Expandable List. It is mainly used when we have data collections whose elements can
change at run time based on user action or any network events. For using this widget we
have to specify the Adapter and Layout Manager.
Basic RecyclerView XML code:

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="abhiandroid.com.recyclerviewexample.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

Gradle Dependency to use RecyclerView:


The RecyclerView widget is a part of separate library valid for API 7 level or higher. Add
the following dependency in your Gradle build file to use recyclerview.
Gradle Scripts > build.gradle and inside dependencies

dependencies {
...
compile "com.android.support:recyclerview-v7:23.0.1"
}

Need of RecyclerView In Android


1. RecyclerView uses a ViewHolder for storing the reference of the view for one
entry in the RecyclerView.
2. When we use ListView or GridView for displaying custom items then we create a
custom xml file and then use it inside our Adapter. For this we create a
CustomAdapter class and then extends our Base or any other Adapter in it.
3. In getView() method of our Adapter we inflate the item layout xml file and then
give the reference of every view by using the unique id’s we provide in our xml
file . Once finished we pass that view to the ListView, ready to be drawn, but the
truth is that ListView and GridView do only half the job of achieving true memory
efficiency.
4. ListView/GridView recycle the item layout but don’t keep the reference to the
layout children, forcing us to call findViewById() for every child of our item layout
for every time we call getView(). This issue causes the scrolling or non responsive
problem as it frantically tries to grab references to the view’s we needed.
5. With the arrival of RecyclerView everything is changed. RecyclerView still uses
Adapter to act as Data source but in this we have to create a ViewHolder to keep
the reference of View in memory, so when we need a new view it either creates a
new ViewHolder object to inflate the layout and hold those references or it
recycles one from existing stack.

RecyclerView v/s ListView

There are lots of new extended functionalities available in RecyclerView that are not
directly supported by ListView as following:

1. Direct horizontal scrolling is not supported in ListView. Whereas in


RecyclerView you can easily implement horizontal and vertical scrolling.
2. ListView supports only simple linear list view with vertical scrolling. Whereas
RecyclerView supports three types of lists using RecyclerView.LayoutManager. 1)
StaggeredGridLayoutManager 2) GridLayoutManager, 3)
LinearLayoutManager. I will give you brief introduction about all these 3 lists
later.
3. ListView gives you an option to add divider using dividerHeight parameter
whereas RecyclerView enable you to customize divider (spacing) between two
elements using RecyclerView.ItemDecoration class.
Android recyclerview vertical list
tutorial (https://iteritory.com/android-recyclerview-horizontal-
list-tutorial/)
Android ListView is a widget that displays a list of vertically scroll-able
items. While implementing listview, we use an adapter that inserts the
items in the list from a source like database query etc.
With recyclerview, Android addressed multiple limitations of listview
and also made it more efficient. For example, recyclerview has built-in
support for animation which was not the case in listview. Recyclerview
forces using the ViewHolder pattern. With recyclerview, we can
implement both vertical and horizontal scrolling. But in listview, only
vertical scrolling is enabled.

Basic tasks for implementing recyclerview


Following are the 5 basic tasks while implementing recyclerview –

1. Add recycler view to activity_main


2. Create a layout xml depicting an item in the list
3. Data model to feed recyclerview
4. Custom adapter for the recyclerview
5. Link customer adapter to recyclerview

Add recyclerview dependency


implementation ‘com.android.support:recyclerview-v7:26.1.0’.

Add recyclerview widget to activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.iteritory.itcrecyclerviewverticallist.MainActivity">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
 
        <android.support.v7.widget.RecyclerView
            android:id="@+id/idRecyclerViewVerticalList"
            android:scrollbars="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
</RelativeLayout >

Add layout file depicting an item in the


vertical list
Right click on res -> layout folder and then click on New –> Layout
resource file menu item. A dialog box will open up; provide the File
name as “vertical_list_grocery_item” and click OK button. Add an
imageview and textview in the layout file. This is the layout of how
each item in list will look like. 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
 
    <ImageView
        android:id="@+id/idProductImage"
        android:layout_width="50dp"
        android:layout_height="50dp"/>
    <TextView
        android:id="@+id/idProductName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30dp"/>
</LinearLayout>

Write Data Model


Next, we will write a model class (Grocery.java) depicting a grocery
item in our list. We’ll use following fields –

1. an image to display the picture of the grocery product


2. Name of the product
Create a new package called model

public class Grocery {


    public int productImage;
    public String productName;
 
    public Grocery(String productName, int productImage) {
        this.productImage = productImage;
        this.productName = productName;
    }
 
    public int getProductImage() {
        return productImage;
    }
 
    public void setProductImage(int productImage) {
        this.productImage = productImage;
    }
 
    public String getProductName() {
        return productName;
    }
 
    public void setProductName(String productName) {
        this.productName = productName;
    }
}

Write custom adapter for the recyclerview


Next, we will create a custom adapter class that will inflate the layout
file vertical_list_grocery_item.xml (that we created above). Create a
new package called adapter inside com.iteritory.itcrecyclerviewverticallist.
Write the adapter class inside adapter package.
The customer adapter class extends RecyclerView.Adapter and
overrides 3 methods –

1. onCreateViewHolder() – inflates the grocery_item.xml layout


2. onBindViewHolder() – the data (product image, product name) is
retrieved from the object and is set to each item/row in the list.
We’ll also override imageView onClick method to display a toast
saying which item is selected.
3. getItemCount() – returns the numbers of items/rows in the list.
We have also defined the view holder in the same adapter class. All
combined, the adapter class looks like –
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
 
import com.iteritory.itcrecyclerviewverticallist.R;
import com.iteritory.itcrecyclerviewverticallist.model.Grocery;
 
import java.util.List;
 
/**
* Created by Sadruddin on 12/9/2017.
*/
 
public class RecyclerViewVerticalListAdapter  extends
RecyclerView.Adapter<RecyclerViewVerticalListAdapter.GroceryViewHolder>{
    private List<Grocery> verticalGrocderyList;
    Context context;
 
    public RecyclerViewVerticalListAdapter(List<Grocery> verticalGrocderyList, Context context){
        this.verticalGrocderyList= verticalGrocderyList;
        this.context = context;
    }
 
    @Override
    public GroceryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //inflate the layout file
        View groceryProductView = LayoutInflater.from(parent.getContext()).inflate(R.layout.vertical_list_grocery_item, parent,
false);
        GroceryViewHolder gvh = new GroceryViewHolder(groceryProductView);
        return gvh;
    }
 
    @Override
    public void onBindViewHolder(GroceryViewHolder holder, final int position) {
        holder.imageView.setImageResource(verticalGrocderyList.get(position).getProductImage());
        holder.txtview.setText(verticalGrocderyList.get(position).getProductName());
        holder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String productName = verticalGrocderyList.get(position).getProductName().toString();
                Toast.makeText(context, productName + " is selected", Toast.LENGTH_SHORT).show();
            }
        });
    }
 
    @Override
    public int getItemCount() {
        return verticalGrocderyList.size();
    }
 
    public class GroceryViewHolder extends RecyclerView.ViewHolder {
 
        ImageView imageView;
        TextView txtview;
        public GroceryViewHolder(View view) {
            super(view);
            imageView=view.findViewById(R.id.idProductImage);
            txtview=view.findViewById(R.id.idProductName);
        }
    }
}
Stitch all together in MainActivity
We have written so many components so far. Now it is the time to
stitch it together to render a vertical list using recyclerview. Here in
this class, we will –

1. instantiate the custom adapter


2. Set a layout manager for the recycler view
3. Link recycler view with the custom adater
4. Feed data and refresh the adapter
5. Well!! that’s it, we’ll have our recycler view working fine and
awesome.
Let’s take a look how our MainActivity.java looks like post all
modification 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
 
import com.iteritory.itcrecyclerviewverticallist.adapter.RecyclerViewVerticalListAdapter;
import com.iteritory.itcrecyclerviewverticallist.model.Grocery;
 
import java.util.ArrayList;
import java.util.List;
 
public class MainActivity extends AppCompatActivity {
 
    private List<Grocery> groceryList = new ArrayList<>();
    private RecyclerView groceryRecyclerView;
    private RecyclerViewVerticalListAdapter groceryAdapter;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        groceryRecyclerView = findViewById(R.id.idRecyclerViewVerticalList);
        // add a divider after each item for more clarity
        groceryRecyclerView.addItemDecoration(new DividerItemDecoration(MainActivity.this,
LinearLayoutManager.VERTICAL));
        groceryAdapter = new RecyclerViewVerticalListAdapter(groceryList, getApplicationContext());
        LinearLayoutManager verticalLayoutManager = new LinearLayoutManager(MainActivity.this,
LinearLayoutManager.VERTICAL, false);
        groceryRecyclerView.setLayoutManager(verticalLayoutManager);
        groceryRecyclerView.setAdapter(groceryAdapter);
        populategroceryList();
    }
 
    private void populategroceryList(){
        Grocery potato = new Grocery("Potato", R.drawable.potato);
        Grocery onion = new Grocery("Onion", R.drawable.onion);
        Grocery cabbage = new Grocery("Cabbage", R.drawable.cabbage);
        Grocery cauliflower = new Grocery("Cauliflower", R.drawable.cauliflower);
        groceryList.add(potato);
        groceryList.add(onion);
        groceryList.add(cabbage);
        groceryList.add(cauliflower);
        groceryAdapter.notifyDataSetChanged();
    }
}

Android Cardview tutorial with example


(https://iteritory.com/android-cardview-tutorial-with-example/)

Cardview is a very powerful UI tool. You may add photo, texts, links
etc in a card to give your user one nice representation of the
information you want to share. By combining recyclerview and
cardview, we can give our apps a beautiful representation.

Basic tasks for implementing cardview


Following are the  basic tasks while implementing cardview –

1. Add the dependency for cardview and recyclerview.


2. Write a model class for the information  you want to display in
the cardview. In my case it’s grocery items
3. Write a XML layout file to depict information visually on the card
view/recycler view.
4. Write a custom adapter to inflate the recyclerview.
5. Modify the acitivity_main.xml to include recyclerview
6. And finally harness these changes from MainActivity.java;
populate data
7. And that’s it. You just understood the basic skeleton of a
cardview project.

Add CardView dependency


dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support:cardview-v7:27.1.0'
    implementation 'com.android.support:recyclerview-v7:27.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Add CardView to the layout file


Next, we will add the CardView widget in the layout file. Inside the
CardView widget, we can use the container view like LinearLayout or
RelativeLayout as the child. Inside the container view, we can add the
other widgets to represent image, text, button etc. For now, let’s just
create a simplest cardview app with a simple text. Open the
activity_main.xml and modify it; add the cardview widget. After doing
the necessary modification, my activity_main.xml looks like –

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <android.support.v7.widget.CardView
        android:id="@+id/idCardView"
        android:layout_margin="20dp"
        android:layout_width="250dp"
        android:layout_height="250dp"
        app:cardCornerRadius="4dp">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="Hello World! This is the initial card view!!" />
    </android.support.v7.widget.CardView>
</LinearLayout>

Write a Model Class depicting Product


Now, we will write a model class depicting the grocery item. We’ll use
following fields –

 an image to display the picture of the grocery product


 Product name
 Price
 Weight
 Quantity

Create Grocery.java model class inside this newly created package.


The class looks like –

public class Grocery {


    public int productImage;
    public String productName;
    public String productPrice;
    public String productWeight;
    public String productQty;
 
    public Grocery(String productName, int productImage, String productPrice, String productWeight, String productQty) {
        this.productImage = productImage;
        this.productName = productName;
        this.productPrice = productPrice;
        this.productWeight = productWeight;
        this.productQty = productQty;
    }
 
    public String getProductQty() {
        return productQty;
    }
 
    public void setProductQty(String productQty) {
        this.productQty = productQty;
    }
 
    public String getProductPrice() {
        return productPrice;
    }
 
    public void setProductPrice(String productPrice) {
        this.productPrice = productPrice;
    }
 
    public String getProductWeight() {
        return productWeight;
    }
 
    public void setProductWeight(String productWeight) {
        this.productWeight = productWeight;
    }
 
    public int getProductImage() {
        return productImage;
    }
 
    public void setProductImage(int productImage) {
        this.productImage = productImage;
    }
 
    public String getProductName() {
        return productName;
    }
 
    public void setProductName(String productName) {
        this.productName = productName;
    }
}

Write a Layout XML depicting Product


Now, we will write a layout file that will depict one grocery item in the
list. Under the res -> layout folder, create a new file with
name layout_product_card.xml. After the necessary updates, my layout
looks as follows –
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingTop="10dp"
    android:paddingBottom="10dp">
        <android.support.v7.widget.CardView
            android:id="@+id/idCardView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:elevation="7dp"
            android:layout_margin="7dp"
            app:cardCornerRadius="6dp"
            app:cardPreventCornerOverlap="false">
 
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@color/cardview_light_background"
                android:orientation="horizontal"
                android:padding="10dp">
 
                <!-- Product Image -->
 
                <LinearLayout
                    android:id="@+id/idLinearLayoutProductImage"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true">
                    <ImageView
                        android:id="@+id/idProductImage"
                        android:layout_width="50dp"
                        android:layout_height="50dp"/>
                </LinearLayout>
 
                <!-- Rest of the product info and add/remove to/from cart symbols -->
 
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:orientation="horizontal"
                    android:id="@+id/idTopLayout">
 
                        <TextView
                            android:id="@+id/idProductName"
                            android:layout_width="250dp"
                            android:layout_height="wrap_content"
                            android:layout_alignParentTop="true"
                            android:layout_toRightOf="@+id/idLinearLayout"
                            android:gravity="center_vertical|center_horizontal"
                            android:textSize="25dp"
                            tools:textColor="@android:color/black" />
 
                        <ImageView
                            android:id="@+id/idMinusICon"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/minus_circle" />
                        <TextView
                            android:id="@+id/idProductQty"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center_vertical|center_horizontal"
                            android:textSize="20dp"
                            tools:textColor="@android:color/black"
                            android:textStyle="bold" />
                        <ImageView
                            android:id="@+id/idPlusIcon"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/plus_circle" />
                    </LinearLayout>
 
                    <LinearLayout
                        android:id="@+id/idBottomLayout"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_below="@+id/idTopLayout">
 
                    <TextView
                        android:id="@+id/idProductPrice"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_marginLeft="100dp"
                        android:layout_weight="1"
                        android:paddingRight="15dp"
                        android:textSize="15dp"
                        android:textStyle="bold"
                        tools:textColor="@android:color/black" />
 
                    <TextView
                        android:id="@+id/idProductWeight"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right|center_vertical"
                        android:paddingRight="45dip"
                        android:textSize="15dp"
                        android:textStyle="bold"
                        tools:textColor="@android:color/black" />
                </LinearLayout>
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

Write custom adapter for the recyclerview


Next, we will create a custom adapter class that will inflate the layout
file layout_product_card.xml (that we created above). Create a new
package called adapter inside com.iteritory.itccardview. Write the adapter
class inside adapter package.
The custom adapter class extends RecyclerView.Adapter and overrides
3 methods –

1. onCreateViewHolder() – inflates the layout_product_card.xml


layout
2. onBindViewHolder() – the data (product image, product name
etc) is retrieved from the object and is set to each item/row in the
list. We’ll also override imageView onClick method to display a
toast saying which item is selected.
3. getItemCount() – returns the numbers of items/rows in the list.
So folks, let’s crack some code.
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
 
import com.iteritory.itccardview.R;
import com.iteritory.itccardview.model.Grocery;
 
import java.util.List;
 
public class GroceryProductAdapter extends RecyclerView.Adapter<GroceryProductAdapter.GroceryProductViewHolder>{
    private List<Grocery> grocderyItemList;
    Context context;
 
    public GroceryProductAdapter(List<Grocery> grocderyItemList, Context context) {
        this.grocderyItemList = grocderyItemList;
        this.context = context;
    }
 
    @Override
    public GroceryProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //inflate the layout file
        View groceryProductView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_product_card, parent, false);
        GroceryProductViewHolder gvh = new GroceryProductViewHolder(groceryProductView);
        return gvh;
    }
 
    @Override
    public void onBindViewHolder(GroceryProductViewHolder holder, final int position) {
        holder.imageProductImage.setImageResource(grocderyItemList.get(position).getProductImage());
        holder.txtProductName.setText(grocderyItemList.get(position).getProductName());
        holder.txtProductPrice.setText(grocderyItemList.get(position).getProductPrice());
        holder.txtProductWeight.setText(grocderyItemList.get(position).getProductWeight());
        holder.txtProductQty.setText(grocderyItemList.get(position).getProductQty());
 
        holder.imageProductImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String productName = grocderyItemList.get(position).getProductName().toString();
                Toast.makeText(context, productName + " is selected", Toast.LENGTH_SHORT).show();
            }
        });
    }
 
    @Override
    public int getItemCount() {
        return grocderyItemList.size();
    }
 
    public class GroceryProductViewHolder extends RecyclerView.ViewHolder {
        ImageView imageProductImage;
        TextView txtProductName;
        TextView txtProductPrice;
        TextView txtProductWeight;
        TextView txtProductQty;
        public GroceryProductViewHolder(View view) {
            super(view);
            imageProductImage=view.findViewById(R.id.idProductImage);
            txtProductName=view.findViewById(R.id.idProductName);
            txtProductPrice = view.findViewById(R.id.idProductPrice);
            txtProductWeight = view.findViewById(R.id.idProductWeight);
            txtProductQty = view.findViewById(R.id.idProductQty);
        }
    }
}

Change activity_main.xml to add recyclerview


Now, we will make minor modification in the activity_main.xml file to
add the recyclerview. Post change, the file content looks like –
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <android.support.v7.widget.RecyclerView
        android:id="@+id/idRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:scrollbars="vertical" />
</LinearLayout>

Update MainActivity.java to add data and


populate the cardview
Finally it’s time to update MainActivity.java file to harness all these
activities that we did so far. Let’s take a look at the code –
package com.iteritory.itccardview;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.iteritory.itccardview.adapter.GroceryProductAdapter;
import com.iteritory.itccardview.model.Grocery;
 
import java.util.ArrayList;
import java.util.List;
 
public class MainActivity extends AppCompatActivity {
 
    private RecyclerView mRecyclerView;
    private GroceryProductAdapter mAdapter;
    private List<Grocery> mProductList;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //getting the recyclerview from xml
        mRecyclerView = (RecyclerView) findViewById(R.id.idRecyclerView);
        //mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
 
        //Populate the products
        mProductList = new ArrayList<>();
        mProductList.add(new Grocery("Mango",R.drawable.mango,"Rs. 150", "1 kg", "5"));
        mProductList.add(new Grocery("Pineapple",R.drawable.pineapple,"Rs. 250", "500 gm", "2"));
 
        //set adapter to recyclerview
        mAdapter = new GroceryProductAdapter(mProductList,this);
        mRecyclerView.setAdapter(mAdapter);
    }
}
Android - Sending Email
To send an email from your application, you don’t have to implement an email client
from the beginning, but you can use an existing one like the default Email app provided
from Android, Gmail, Outlook, K-9 Mail etc. For this purpose, we need to write an
Activity that launches an email client, using an implicit Intent with the right action and
data. In this example, we are going to send an email from our app by using an Intent
object that launches existing email clients.
Following section explains different parts of our Intent object required to send an email.

Intent Object - Action to send Email


You will use ACTION_SEND action to launch an email client installed on your Android
device. Following is simple syntax to create an intent with ACTION_SEND action.
Intent emailIntent = new Intent(Intent.ACTION_SEND);

Intent Object - Data/Type to send Email


To send an email you need to specify mailto: as URI using setData() method and data
type will be to text/plain using setType() method as follows −
emailIntent.setData(Uri.parse("mailto:"));
emailIntent.setType("text/plain");

Intent Object - Extra to send Email


Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which can be
attached to the intent before sending the intent to a target email client. You can use
following extra fields in your email −

Sr.No Extra Data & Description


.

1
EXTRA_BCC
A String[] holding e-mail addresses that should be blind carbon copied.

2
EXTRA_CC
A String[] holding e-mail addresses that should be carbon copied.
3
EXTRA_EMAIL
A String[] holding e-mail addresses that should be delivered to.

4
EXTRA_HTML_TEXT
A constant String that is associated with the Intent, used with ACTION_SEND to
supply an alternative to EXTRA_TEXT as HTML formatted text.

5
EXTRA_SUBJECT
A constant string holding the desired subject line of a message.

6
EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent.

7
EXTRA_TITLE
A CharSequence dialog title to provide to the user when used with a
ACTION_CHOOSER.

Here is an example showing you how to assign extra data to your intent −
emailIntent.putExtra(Intent.EXTRA_EMAIL , new String[]
{"Recipient"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject");
emailIntent.putExtra(Intent.EXTRA_TEXT , "Message Body");

You might also like