Android Examples
Android Examples
Android Examples
AutoCompleteTextView is an editable text view which is used to show the list of suggestions based
on the user typing text.
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
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.
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" />
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.
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
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" />
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="calendar"/>
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"/>
<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());
}
});
}
}
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.
<TimePicker android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="clock" />
<TimePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"/>
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.
In anroid, the SeekBar supports two types of modes to show the progress, those
are Determinate and Indeterminate.
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.
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:max="100"
android:progress="50" />
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.
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());
}
});
}
}
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.
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.
setTitle() It is used to set the title of alertdialog and its an optional component.
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.
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();
}
});
}
}
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.
<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.
android:showAsActio It is used to specify how the item should appear as an action item in the
n app bar.
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.
onActivityCreated( It is called when the fragment activity has been created and the fragment
) view hierarchy instantiated.
onPause() It is called when fragment is no longer visible and it indicates that the user is
leaving the fragment.
onDestoryView() The view hierarcy which associated with the fragment is being removed after
executing this method.
onDetach() It is called immediately after the fragment disassociated from the activity.
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>
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>
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.
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.
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>
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>
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.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);
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 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
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.
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
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.
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.
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.
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.
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>
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.
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 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.
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.
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>
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.
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:
dependencies {
...
compile "com.android.support:recyclerview-v7:23.0.1"
}
There are lots of new extended functionalities available in RecyclerView that are not
directly supported by ListView as following:
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.
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");