Android is a software package and linux based operating system for mobile devices such as tablet computers and smartphones. It is developed by Google and later the OHA (Open Handset Alliance). Java language is mainly used to write the android code even though other languages can be used. The goal of android project is to create a successful real-world product that improves the mobile experience for end users. There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream Sandwich, Froyo, Ecliar, Donut etc which is covered in next page.
What is Open Handset Alliance (OHA) It's a consortium of 84 companies such as google, samsung, AKM, synaptics, KDDI, Garmin, Teleca, Ebay, Intel etc. It was established on 5th November, 2007, led by Google. It is committed to advance open standards, provide services and deploy handsets using the Android Plateform.
Features of Android After learning what is android, let's see the features of android. The important features of android are given below: 1) It is open-source. 2) Anyone can customize the Android Platform. 3) There are a lot of mobile applications that can be chosen by the consumer. 4) It provides many interesting features like weather details, opening screen, live RSS (Really Simple Syndication) feeds etc. It provides support for messaging services(SMS and MMS), web browser, storage (SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout etc.
Categories of Android applications There are many android applications in the market. The top categories are:
o
Entertainment
o
Tools
o
Communication
o
Productivity
o
Personalization
o
Music and Audio
o
Social
o
Media and Video
o
Travel and Local etc.
History of Android The history and versions of android are interesting to know. The code names of android ranges from A to J currently, such as Aestro, Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat and Lollipop. Let's understand the android history in a sequence. 1) Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United States in October, 2003. 2) In 17th August 2005, Google acquired android Incorporation. Since then, it is in the subsidiary of Google Incorporation. 3) The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris White and Nick Sears. 4) Originally intended for camera but shifted to smart phones later because of low market for camera only. 5) Android is the nick name of Andy Rubin given by coworkers because of his love to robots. 6) In 2007, Google announces the development of android OS. 7) In 2008, HTC launched the first android mobile.
Android Versions, Codename and API Let's see the android versions, codenames and API Level provided by Google.
Version
Code name
API Level
1.5
Cupcake
3
1.6
Donut
4
2.1
Eclair
7
2.2
Froyo
8
2.3
Gingerbread
9 and 10
3.1 and 3.3
Honeycomb
12 and 13
4.0
Ice Cream Sandwitch
15
4.1, 4.2 and 4.3
Jelly Bean
16, 17 and
4.4
KitKat
19
5.0
Lollipop
21
Android Architecture android architecture or Android software stack is categorized into five parts: 1. linux kernel 2. native libraries (middleware), 3. Android Runtime 4. Application Framework 5. Applications Let's see the android architecture first.
1) Linux kernel It is the heart of android architecture that exists at the root of android architecture. Linux kernel is responsible for device drivers, power management, memory management, device management and resource access.
2) Native Libraries On the top of linux kernel, their are Native libraries such as WebKit, OpenGL, FreeType, SQLite, Media, C runtime library (libc) etc. The WebKit library is responsible for browser support, SQLite is for database, FreeType for font support, Media for playing and recording audio and video formats.
3) Android Runtime In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is responsible to run android application. DVM is like JVM but it is optimized for mobile devices. It consumes less memory and provides fast performance.
4) Android Framework On the top of Native libraries and android runtime, there is android framework. Android framework includes Android API's such as UI (User Interface), telephony, resources, locations, Content Providers (data) and package managers. It provides a lot of classes and interfaces for android application development.
5) Applications On the top of android framework, there are applications. All applications such as home, contact, settings, games, browsers are using android framework that uses android runtime and libraries. Android runtime and native libraries are using linux kernal.
Android Core Building Blocks An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, Service etc.
The core building blocks or fundamental components of android are activities, views, intents, services, content providers, fragments and AndroidManifest.xml.
Activity An activity is a class that represents a single screen. It is like a Frame in AWT.
View A view is the UI element such as button, label, text field etc. Anything that you see is a view.
Intent Intent is used to invoke components. It is mainly used to: o
Start the service
o
Launch an activity
o
Display a web page
o
Display a list of contacts
o
Broadcast a message
o
Dial a phone call etc.
For example, you may write the following code to view the webpage. 1. Intent intent=new Intent(Intent.ACTION_VIEW); 2. intent.setData(Uri.parse("http://www.javatpoint.com")); 3. startActivity(intent);
Service Service is a background process that can run for a long time. There are two types of services local and remote. Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device.
Content Provider Content Providers are used to share data between the applications.
Fragment Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same time.
AndroidManifest.xml It contains informations about activities, content providers, permissions etc. It is like the web.xml file in Java EE.
Android Virtual Device (AVD) It is used to test the android application without the need for mobile or tablet etc. It can be created in different configurations to emulate different types of real devices.
Android Emulator Android Emulator is used to run, debug and test the android application. If you don't have the real device, it can be the best way to run, debug and test the application. It uses an open source processor emulator technology called QEMU. The emulator tool enables you to start the emulator from the command line. You need to write: emulator -avd
In case of Eclipse IDE, you can create AVD by Window menu > AVD Manager > New. In the given image, you can see the android emulator, it displays the output of the hello android example.
Dalvik Virtual Machine | DVM As we know the modern JVM is high performance and provides excellent memory management. But it needs to be optimized for low-powered handheld devices as well. The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile devices. It optimizes the virtual machine for memory, battery life and performance. Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple class files are converted into one dex file. Let's see the compiling and packaging process from the source file:
The javac tool compiles the java source file into the class file. The dx tool takes all the class files of your application and generates a single .dex file. It is a platform-specific tool. The Android Assets Packaging Tool (aapt) handles the packaging process. next →← prev
AndroidManifest.xml file in android The AndroidManifest.xml file contains information of your package, including components of the application such as activities, services, broadcast receivers, content providers etc. It performs some other tasks also: o
It is responsible to protect the application to access any protected parts by providing the permissions.
o
It also declares the android api that the application is going to use.
o
It lists the instrumentation classes. The instrumentation classes provides profiling and other informations. These informations are removed just before the application is published etc.
This is the required xml file for all the android application and located inside the root directory. A simple AndroidManifest.xml file looks like this: 1. <manifest xmlns:android="http://schemas.android.com/apk/res/android" 2.
package="com.javatpoint.hello"
3.
android:versionCode="1"
4.
android:versionName="1.0" >
5.
6.
<uses-sdk
7.
android:minSdkVersion="8"
8.
android:targetSdkVersion="15" />
9. 10.
11.
android:icon="@drawable/ic_launcher"
12.
android:label="@string/app_name"
13.
android:theme="@style/AppTheme" rel="nofollow">
14.
15.
android:name=".MainActivity"
16.
android:label="@string/title_activity_main" rel="nofollow">
17.
18.
19. 20. 21. 22. 23.
24. 25.
Elements of the AndroidManifest.xml file The elements used in the above xml file are described below.
<manifest> manifest is the root element of the AndroidManifest.xml file. It has package attribute that describes the package name of the activity class.
application is the subelement of the manifest. It includes the namespace declaration. This element contains several subelements that declares the application component such as activity etc. The commonly used attributes are of this element are icon, label, theme etc.
android:icon represents the icon for all the android application components. android:label works as the default label for all the application components. android:theme represents a common theme for all the android activities.
activity is the subelement of application and represents an activity that must be defined in the AndroidManifest.xml file. It has many attributes such as label, name, theme, launchMode etc. android:label represents a label i.e. displayed on the screen. android:name represents a name for the activity class. It is required attribute.
intent-filter is the sub-element of activity that describes the type of intent to which activity, service or broadcast receiver can respond to.
It adds an action for the intent-filter. The intent-filter must have at least one action element.
It adds a category name to an intent-filter.
Android R.java file Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains resource IDs for all the resources of res/ directory. If you create any component in the activity_main.xml file, id for the corresponding component is automatically created in this file. This id can be used in the activity source file to perform any action on the component.
Android Screen Orientation Example The screenOrientation is the attribute of activity element. The orientation of android activity can be portrait, landscape, sensor, unspecified etc. You need to define it in the AndroidManifest.xml file. For example: 1.
android:name="com.example.screenorientation.MainActivity"
3.
android:label="@string/app_name"
4.
android:screenOrientation="landscape"
5.
rel="nofollow"> The common values for screenOrientation attribute are as follows:
Value
Description
unspecified
It is the default value. In such case, system chooses the orientation.
portrait
taller not wider
landscape
wider not taller
sensor
orientation is determined by the device orientation sensor.
Android Button Example Android Button represents a push-button. The android.widget.Button is subclass of TextView class and CompoundButton is the subclass of Button class. There are different types of buttons in android such as RadioButton, ToggleButton, CompoundButton etc. Here, we are going to create two textfields and one button for sum of two numbers. If user clicks button, sum of two input values is displayed on the Toast.
Drag the component activity_main.xml
or
write
the
code
for
UI
in
First of all, drag 2 textfields from the Text Fields palette and one button from the Form Widgets palette as shown in the following figure.
The generated code for the ui components will be like this:
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
<EditText
8.
android:id="@+id/editText1"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentTop="true"
12.
android:layout_centerHorizontal="true"
13.
android:layout_marginTop="24dp"
14.
android:ems="10" />
15. 16.
<EditText
17.
android:id="@+id/editText2"
18.
android:layout_width="wrap_content"
19.
android:layout_height="wrap_content"
20.
android:layout_alignLeft="@+id/editText1"
21.
android:layout_below="@+id/editText1"
22.
android:layout_marginTop="34dp"
23.
android:ems="10" >
24. 25. 26. 27.
<requestFocus />
28.
<Button
29.
android:id="@+id/button1"
30.
android:layout_width="wrap_content"
31.
android:layout_height="wrap_content"
32.
android:layout_centerHorizontal="true"
33.
android:layout_centerVertical="true"
34.
android:text="@string/Button" />
35. 36.
Activity class Now write the code to display the sum of two numbers.
File: MainActivity.java 1. package com.example.sumof2numbers; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.view.Menu; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.Button; 9. import android.widget.EditText; 10. import android.widget.Toast; 11. 12. public class MainActivity extends Activity { 13.
private EditText edittext1,edittext2;
14.
private Button buttonSum;
15.
@Override
16.
protected void onCreate(Bundle savedInstanceState) {
17.
super.onCreate(savedInstanceState);
18.
setContentView(R.layout.activity_main);
19. 20.
addListenerOnButton();
21. 22.
}
23.
public void addListenerOnButton(){
24.
edittext1=(EditText)findViewById(R.id.editText1);
25.
edittext2=(EditText)findViewById(R.id.editText2);
26.
buttonSum=(Button)findViewById(R.id.button1);
27. 28.
buttonSum.setOnClickListener(new OnClickListener(){
29. 30.
@Override
31.
public void onClick(View view) {
32.
String value1=edittext1.getText().toString();
33.
String value2=edittext2.getText().toString();
34.
int a=Integer.parseInt(value1);
35.
int b=Integer.parseInt(value2);
36.
int sum=a+b;
37.
Toast.makeText(getApplicationContext(),String.valueOf(sum),Toast.LENGTH_LONG).sho w();
38.
}
39. 40.
});
41. 42.
}
43.
@Override
44.
public boolean onCreateOptionsMenu(Menu menu) {
45.
// Inflate the menu; this adds items to the action bar if it is present.
46.
getMenuInflater().inflate(R.menu.activity_main, menu);
47.
return true;
48.
}
49. 50. }
Toast class Toast class is used to show notification for a particular interval of time. After sometime it disappears. It doesn't block the user interaction.
Constants of Toast class There are only 2 constants of Toast class which are given below.
Constant
Description
public static final int LENGTH_LONG
displays view for the long duration of time.
public static final int LENGTH_SHORT
displays view for the short duration of time
Methods of Toast class The widely used methods of Toast class are given below.
Method public static Toast makeText(Context context, CharSequence text, int
Description
makes the toast containing
duration)
public void show()
displays toast.
public void setMargin (float horizontalMargin, float verticalMargin)
changes the horizontal a difference.
Android Toast Example 1. Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show(); Another code: 1. Toast toast=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHO RT); 2. toast.setMargin(50,50); 3. toast.show(); Here, getApplicationContext() method returns the instance of Context.
Full code of activity class displaying Toast Let's see the code to display the toast.
File: MainActivity.java 1. package com.example.toast; 2. import android.os.Bundle; 3. import android.app.Activity; 4. import android.view.Menu; 5. import android.view.View; 6. import android.widget.Toast; 7. 8. public class MainActivity extends Activity { 9.
@Override
10.
public void onCreate(Bundle savedInstanceState) {
11.
super.onCreate(savedInstanceState);
12.
setContentView(R.layout.activity_main);
13. 14.
//Displaying Toast with Hello Javatpoint message
15.
Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT). show();
16.
}
17. 18.
@Override
19.
public boolean onCreateOptionsMenu(Menu menu) {
20.
getMenuInflater().inflate(R.menu.activity_main, menu);
21.
return true;
22.
}
23. }
Android ToggleButton class
ToggleButton class provides the facility of creating the toggle button.
XML Attributes of ToggleButton class The 3 XML attributes of ToggleButton class.
XML Attribute
Description
android:disabledAlpha
The alpha to apply to the indicator when disabled.
android:textOff
The text for the button when it is not checked.
android:textOn
The text for the button when it is checked.
Methods of ToggleButton class The widely used methods of ToggleButton class are given below.
Method
Description
CharSequence getTextOff()
Returns the text when button is not in the checked state.
CharSequence getTextOn()
Returns the text for when button is in the checked state.
void setChecked(boolean checked)
Changes the checked state of this button.
Android ToggleButton Example activity_main.xml Drag two toggle button and one button for the layout. Now the activity_main.xml file will look like this:
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6.
7.
8.
android:id="@+id/toggleButton1"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentLeft="true"
12.
android:layout_alignParentTop="true"
13.
android:layout_marginLeft="60dp"
14.
android:layout_marginTop="18dp"
15.
android:text="ToggleButton1"
16.
android:textOff="Off"
17.
android:textOn="On" />
18. 19.
20.
android:id="@+id/toggleButton2"
21.
android:layout_width="wrap_content"
22.
android:layout_height="wrap_content"
23.
android:layout_alignBaseline="@+id/toggleButton1"
24.
android:layout_alignBottom="@+id/toggleButton1"
25.
android:layout_marginLeft="44dp"
26.
android:layout_toRightOf="@+id/toggleButton1"
27.
android:text="ToggleButton2"
28.
android:textOff="Off"
29.
android:textOn="On" />
30. 31.
<Button
32.
android:id="@+id/button1"
33.
android:layout_width="wrap_content"
34.
android:layout_height="wrap_content"
35.
android:layout_below="@+id/toggleButton2"
36.
android:layout_marginTop="82dp"
37.
android:layout_toRightOf="@+id/toggleButton1"
38.
android:text="submit" />
39. 40.
Activity class Let's write the code to check which toggle button is ON/OFF.
File: MainActivity.java 1. package com.example.togglebutton; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.view.Menu; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.Button; 9. import android.widget.Toast; 10. import android.widget.ToggleButton; 11. 12. public class MainActivity extends Activity { 13.
private ToggleButton toggleButton1, toggleButton2;
14.
private Button buttonSubmit;
15.
@Override
16.
protected void onCreate(Bundle savedInstanceState) {
17.
super.onCreate(savedInstanceState);
18.
setContentView(R.layout.activity_main);
19. 20.
addListenerOnButtonClick();
21.
}
22.
public void addListenerOnButtonClick(){
23.
//Getting the ToggleButton and Button instance from the layout xml file
24.
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton1);
25.
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
26.
buttonSubmit=(Button)findViewById(R.id.button1);
27. 28.
//Performing action on button click
29.
buttonSubmit.setOnClickListener(new OnClickListener(){
30. 31.
@Override
32.
public void onClick(View view) {
33.
StringBuilder result = new StringBuilder();
34.
result.append("ToggleButton1 : ").append(toggleButton1.getText());
35.
result.append("\nToggleButton2 : ").append(toggleButton2.getText());
36.
//Displaying the message in toast
37.
Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG) .show();
38.
}
39. 40.
});
41. 42.
}
43.
@Override
44.
public boolean onCreateOptionsMenu(Menu menu) {
45.
// Inflate the menu; this adds items to the action bar if it is present.
46.
getMenuInflater().inflate(R.menu.activity_main, menu);
47.
return true;
48.
}
49. 50. }
Android CheckBox class The android.widget.CheckBox class provides the facility of creating the CheckBoxes.
Methods of CheckBox class There are many inherited methods of View, TextView, and Button classes in the CheckBox class. Some of them are as follows:
Method
Description
public boolean isChecked()
Returns true if it is checked otherwise fals
public void setChecked(boolean status)
Changes the state of the CheckBox.
Android CheckBox Example
activity_main.xml Drag the three checkboxes and one button for the layout. Now the activity_main.xml file will look like this:
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
8.
android:id="@+id/checkBox1"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentLeft="true"
12.
android:layout_alignParentTop="true"
13.
android:text="Pizza" />
14. 15.
16.
android:id="@+id/checkBox2"
17.
android:layout_width="wrap_content"
18.
android:layout_height="wrap_content"
19.
android:layout_alignParentTop="true"
20.
android:layout_toRightOf="@+id/checkBox1"
21.
android:text="Coffe" />
22. 23.
24.
android:id="@+id/checkBox3"
25.
android:layout_width="wrap_content"
26.
android:layout_height="wrap_content"
27.
android:layout_alignParentTop="true"
28.
android:layout_toRightOf="@+id/checkBox2"
29.
android:text="Burger" />
30. 31. 32.
<Button android:id="@+id/button1"
33.
android:layout_width="wrap_content"
34.
android:layout_height="wrap_content"
35.
android:layout_below="@+id/checkBox2"
36.
android:layout_marginTop="32dp"
37.
android:layout_toLeftOf="@+id/checkBox3"
38.
android:text="Order" />
39. 40.
Activity class Let's write the code to check which toggle button is ON/OFF.
File: MainActivity.java 1. package com.example.checkbox; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.view.Menu; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.*; 9. 10. public class MainActivity extends Activity { 11.
CheckBox pizza,coffe,burger;
12.
Button buttonOrder;
13.
@Override
14.
protected void onCreate(Bundle savedInstanceState) {
15.
super.onCreate(savedInstanceState);
16.
setContentView(R.layout.activity_main);
17.
addListenerOnButtonClick();
18.
}
19. public void addListenerOnButtonClick(){ 20.
//Getting instance of CheckBoxes and Button from the activty_main.xml file
21.
pizza=(CheckBox)findViewById(R.id.checkBox1);
22.
coffe=(CheckBox)findViewById(R.id.checkBox2);
23.
burger=(CheckBox)findViewById(R.id.checkBox3);
24.
buttonOrder=(Button)findViewById(R.id.button1);
25. 26.
//Applying the Listener on the Button click
27.
buttonOrder.setOnClickListener(new OnClickListener(){
28. 29.
@Override
30.
public void onClick(View view) {
31.
int totalamount=0;
32.
StringBuilder result=new StringBuilder();
33.
result.append("Selected Items:");
34.
if(pizza.isChecked()){
35.
result.append("\nPizza 100Rs");
36.
totalamount+=100;
37.
}
38.
if(coffe.isChecked()){
39.
result.append("\nCoffe 50Rs");
40.
totalamount+=50;
41.
}
42.
if(burger.isChecked()){
43.
result.append("\nBurger 120Rs");
44.
totalamount+=120;
45.
}
46.
result.append("\nTotal: "+totalamount+"Rs");
47.
//Displaying the message on the toast
48.
Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).s how();
49.
}
50. 51.
});
52. } 53.
@Override
54.
public boolean onCreateOptionsMenu(Menu menu) {
55.
// Inflate the menu; this adds items to the action bar if it is present.
56.
getMenuInflater().inflate(R.menu.activity_main, menu);
57.
return true;
58. 59.
}
60. } 1.
2.
android:layout_width="wrap_content"
3.
android:layout_height="wrap_content"
4.
android:id="@+id/radioGroup">
5. 6.
7.
android:id="@+id/radioMale"
8.
android:layout_width="fill_parent"
9.
android:layout_height="wrap_content"
10.
android:text=" Male"
11.
android:layout_marginTop="10dp"
12.
android:checked="false"
13.
android:textSize="20dp" />
14. 15.
16.
android:id="@+id/radioFemale"
17.
android:layout_width="fill_parent"
18.
android:layout_height="wrap_content"
19.
android:text="
20.
android:layout_marginTop="20dp"
21.
android:checked="false"
Female"
22. 23. 24.
android:textSize="20dp" />
25. 26.
<Button
27.
android:layout_width="wrap_content"
28.
android:layout_height="wrap_content"
29.
android:text="Show Selected"
30.
android:id="@+id/button"
31.
android:onClick="onclickbuttonMethod"
32.
android:layout_gravity="center_horizontal" />
33. 34.
Activity class File: MainActivity.java 1. package com.example.gigabit.radiobuttom; 2. 3. import android.support.v7.app.AppCompatActivity; 4. import android.os.Bundle; 5. import android.view.View; 6. import android.widget.Button; 7. import android.widget.RadioButton; 8. import android.widget.RadioGroup; 9. import android.widget.Toast; 10. 11. public class MainActivity extends AppCompatActivity { 12. 13.
Button button;
14.
RadioButton genderradioButton;
15.
RadioGroup radioGroup;
16.
@Override
17.
protected void onCreate(Bundle savedInstanceState) {
18.
super.onCreate(savedInstanceState);
19.
setContentView(R.layout.activity_main);
20. 21.
radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
22.
}
23. 24. 25.
public void onclickbuttonMethod(View v){
26.
int selectedId = radioGroup.getCheckedRadioButtonId();
27.
genderradioButton = (RadioButton) findViewById(selectedId);
28.
if(selectedId==-1){
29.
Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHORT).show ();
30.
}
31.
else{
32.
Toast.makeText(MainActivity.this,genderradioButton.getText(), Toast.LENGTH_SH ORT).show();
33.
}
34. 35.
}
36. }
Android AlertDialog Example Let's see a simple example of android alert dialog.
activity_main.xml You can have multiple components, here we are having only a textview.
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
8.
android:layout_width="wrap_content"
9.
android:layout_height="wrap_content"
10.
android:layout_centerHorizontal="true"
11.
android:layout_centerVertical="true"
12.
android:text="@string/hello_world" />
13. 14.
strings.xml Optionally, you can store the dialog message and title in the strings.xml file.
File: strings.xml 1. 2. 3. 4.
<string name="app_name">alertdialog
5.
<string name="hello_world">Hello world!
6.
<string name="menu_settings">Settings
7.
<string name="dialog_message">Welcome to Alert Dialog
8. 9.
<string name="dialog_title">Javatpoint Alert Dialog
10.
Activity class Let's write the code to create and show the AlertDialog.
File: MainActivity.java 1. package com.example.alertdialog; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.app.AlertDialog; 6. import android.content.DialogInterface; 7. import android.view.Menu; 8. 9. public class MainActivity extends Activity { 10. 11.
@Override
12.
protected void onCreate(Bundle savedInstanceState) {
13.
super.onCreate(savedInstanceState);
14. 15.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
16.
//Uncomment the below code to Set the message and title from the strings.xml file
17.
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
18. 19.
//Setting message manually and performing action on button click
20.
builder.setMessage("Do you want to close this application ?")
21.
.setCancelable(false)
22.
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
23.
public void onClick(DialogInterface dialog, int id) {
24.
finish();
25.
}
26.
})
27.
.setNegativeButton("No", new DialogInterface.OnClickListener() {
28.
public void onClick(DialogInterface dialog, int id) {
29.
// Action for 'NO' Button
30.
dialog.cancel();
31.
}
32.
});
33. 34.
//Creating dialog box
35.
AlertDialog alert = builder.create();
36.
//Setting the title manually
37.
alert.setTitle("AlertDialogExample");
38.
alert.show();
39.
setContentView(R.layout.activity_main);
40.
}
41. 42.
@Override
43.
public boolean onCreateOptionsMenu(Menu menu) {
44.
// Inflate the menu; this adds items to the action bar if it is present.
45.
getMenuInflater().inflate(R.menu.activity_main, menu);
46.
return true;
47.
}
48. 49. } Android Spinner is like the combox box of AWT or Swing.
Android Spinner Example In this example, we are going to display the country list. You need to use ArrayAdapter class to store the country list. Let's see the simple example of spinner in android.
activity_main.xml Drag the Spinner from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
<Spinner
8.
android:id="@+id/spinner1"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentTop="true"
12.
android:layout_centerHorizontal="true"
13.
android:layout_marginTop="83dp" />
14. 15.
Activity class Let's write the code to display item on the spinner and perform event handling.
File: MainActivity.java 1. package com.example.spinner; 2. import android.app.Activity; 3. import android.os.Bundle; 4. import android.view.Menu; 5. import android.view.View; 6. import android.widget.AdapterView; 7. import android.widget.ArrayAdapter; 8. import android.widget.Spinner; 9. import android.widget.TextView; 10. import android.widget.Toast; 11. 12. public class MainActivity extends Activity implements 13. AdapterView.OnItemSelectedListener { 14. 15. 16.
String[] country = { "India", "USA", "China", "Japan", "Other", };
17.
@Override
18.
protected void onCreate(Bundle savedInstanceState) {
19.
super.onCreate(savedInstanceState);
20.
setContentView(R.layout.activity_main);
21.
//Getting the instance of Spinner and applying OnItemSelectedListener on it
22.
Spinner spin = (Spinner) findViewById(R.id.spinner1);
23.
spin.setOnItemSelectedListener(this);
24. 25.
//Creating the ArrayAdapter instance having the country list
26.
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,coun try);
27.
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
28.
//Setting the ArrayAdapter data on the Spinner
29.
spin.setAdapter(aa);
30.
}
31. 32. 33.
//Performing action onItemSelected and onNothing selected
34.
@Override
35.
public void onItemSelected(AdapterView> arg0, View arg1, int position,long id) {
36.
Toast.makeText(getApplicationContext(),country[position] ,Toast.LENGTH_LONG).sho w();
37.
}
38. 39.
@Override
40.
public void onNothingSelected(AdapterView> arg0) {
41.
// TODO Auto-generated method stub
42. 43.
}
44. 45.
@Override
46.
public boolean onCreateOptionsMenu(Menu menu) {
47.
// Inflate the menu; this adds items to the action bar if it is present.
48.
getMenuInflater().inflate(R.menu.activity_main, menu);
49.
return true;
50. 51. }
}
Android AutoCompleteTextView Example In this example, we are displaying the programming languages in the autocompletetextview. All the programming languages are stored in string array. We are using the ArrayAdapter class to display the array content. Let's see the simple example of autocompletetextview in android.
activity_main.xml Drag the AutoCompleteTextView and TextView from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
8.
android:id="@+id/textView1"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentLeft="true"
12.
android:layout_alignParentTop="true"
13.
android:layout_marginTop="15dp"
14.
android:text="@string/what_is_your_favourite_programming_language_" />
15. 16.
17.
android:id="@+id/autoCompleteTextView1"
18.
android:layout_width="wrap_content"
19.
android:layout_height="wrap_content"
20.
android:layout_alignParentLeft="true"
21.
android:layout_below="@+id/textView1"
22.
android:layout_marginLeft="36dp"
23.
android:layout_marginTop="17dp"
24.
android:ems="10"
25.
android:text="" rel="nofollow">
26. 27. 28.
<requestFocus />
29. 30.
Activity class Let's write the code of AutoCompleteTextView.
File: MainActivity.java 1. package com.example.autocompletetextview; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.graphics.Color; 6. import android.view.Menu; 7. import android.widget.ArrayAdapter; 8. import android.widget.AutoCompleteTextView; 9. 10. public class MainActivity extends Activity { 11.
String[] language ={"C","C++","Java",".NET","iPhone","Android","ASP.NET","PHP"};
12.
@Override
13.
protected void onCreate(Bundle savedInstanceState) {
14.
super.onCreate(savedInstanceState);
15.
setContentView(R.layout.activity_main);
16. 17. 18. 19. 20. 21.
//Creating the instance of ArrayAdapter containing list of language names ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.select_dialog_item,language); //Getting the instance of AutoCompleteTextView AutoCompleteTextView actv= (AutoCompleteTextView)findViewById(R.id.autoCompl eteTextView1);
22.
actv.setThreshold(1);//will start working from first character
23.
actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
24.
actv.setTextColor(Color.RED);
25.
26.
}
27. 28.
@Override
29.
public boolean onCreateOptionsMenu(Menu menu) {
30.
// Inflate the menu; this adds items to the action bar if it is present.
31.
getMenuInflater().inflate(R.menu.activity_main, menu);
32.
return true;
33.
}
34. 35. }
ListView Let's implement a simple listview example. Structure of listview project
activity_main.xml First we need to drag and drop ListView component from palette to activity_main.xml file. File: activity_main.xml 1. 2.
xmlns:app="http://schemas.android.com/apk/res-auto"
4.
xmlns:tools="http://schemas.android.com/tools"
5.
android:layout_width="match_parent"
6.
android:layout_height="match_parent"
7.
tools:context="listview.example.com.listview.MainActivity" rel="nofollow">
8. 9.
10.
android:id="@+id/listView"
11.
android:layout_width="match_parent"
12.
android:layout_height="fill_parent"
13.
/>
14.
Create an additional mylist.xml file in layout folder which contains view components displayed in listview.
mylist.xml File: mylist.xml 1. 2. 3.
android:id="@+id/textView"
5.
android:layout_width="wrap_content"
6.
android:layout_height="wrap_content"
7.
android:text="Medium Text"
8.
android:textStyle="bold"
9.
android:textAppearance="?android:attr/textAppearanceMedium"
10.
android:layout_marginLeft="10dp"
11.
android:layout_marginTop="5dp"
12.
android:padding="2dp"
13.
android:textColor="#4d4d4d"
14.
/> Now place the list of data in strings.xml file by creating string-array.
strings.xml File:strings.xml 1. 2.
<string name="app_name">ListView
3.
<string-array name="array_technology">
4.
- Android
5.
- Java
6.
- Php
7.
- Hadoop
8.
- Sap
9.
- Python
10.
- Ajax
11.
- C++
12.
- Ruby
13.
- Rails
14.
- .Net
15.
- Perl
16.
17.
Activity class In java class we need to add adapter to listview using setAdapter() method of listview. File: MainActivity.java 1. package listview.example.com.listview; 2. 3. import android.support.v7.app.AppCompatActivity; 4. import android.os.Bundle; 5. import android.view.View; 6. import android.widget.AdapterView; 7. import android.widget.ArrayAdapter; 8. import android.widget.ListView; 9. import android.widget.TextView; 10. import android.widget.Toast; 11. 12. public class MainActivity extends AppCompatActivity { 13.
ListView listView;
14.
TextView textView;
15.
String[] listItem;
16.
@Override
17.
protected void onCreate(Bundle savedInstanceState) {
18.
super.onCreate(savedInstanceState);
19.
setContentView(R.layout.activity_main);
20. 21.
listView=(ListView)findViewById(R.id.listView);
22.
textView=(TextView)findViewById(R.id.textView);
23.
listItem = getResources().getStringArray(R.array.array_technology);
24.
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
25. 26. 27.
android.R.layout.simple_list_item_1, android.R.id.text1, listItem); listView.setAdapter(adapter);
28.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
29.
@Override
30.
public void onItemClick(AdapterView> adapterView, View view, int position, lo ng l) {
31.
// TODO Auto-generated method stub
32.
String value=adapter.getItem(position);
33.
Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();
34. 35.
}
36.
});
37.
}
38. }
Custom ListView In this custom listview example, we are adding image, text with title and its sub-title. Structure of custom listview project
activity_main.xml Create an activity_main.xml file in layout folder. File: activity_main.xml 1. 2.
xmlns:tools="http://schemas.android.com/tools"
4.
android:layout_width="match_parent"
5.
android:layout_height="match_parent"
6.
android:paddingBottom="@dimen/activity_vertical_margin"
7.
android:paddingLeft="@dimen/activity_horizontal_margin"
8.
android:paddingRight="@dimen/activity_horizontal_margin"
9.
android:paddingTop="@dimen/activity_vertical_margin"
10.
tools:context="com.example.test.listviewwithimage.MainActivity">
11. 12.
13.
android:id="@+id/list"
14.
android:layout_width="match_parent"
15.
android:layout_height="wrap_content"
16.
android:layout_marginBottom="50dp">
17.
18. Create an additional mylist.xml file in layout folder which contains view components displayed in listview.
mylist.xml File: mylist.xml 1. 2.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
android:orientation="horizontal" >
6. 7.
8.
android:id="@+id/icon"
9.
android:layout_width="60dp"
10.
android:layout_height="60dp"
11.
android:padding="5dp" />
12. 13.
14.
android:layout_height="wrap_content"
15.
android:orientation="vertical">
16. 17.
18.
android:id="@+id/title"
19.
android:layout_width="wrap_content"
20.
android:layout_height="wrap_content"
21.
android:text="Medium Text"
22.
android:textStyle="bold"
23.
android:textAppearance="?android:attr/textAppearanceMedium"
24.
android:layout_marginLeft="10dp"
25.
android:layout_marginTop="5dp"
26.
android:padding="2dp"
27.
android:textColor="#4d4d4d" />
28.
29.
android:id="@+id/subtitle"
30.
android:layout_width="wrap_content"
31.
android:layout_height="wrap_content"
32.
android:text="TextView"
33.
android:layout_marginLeft="10dp"/>
34.
35. Place the all required images in drawable folder.
Activity class File: MainActivity.java 1. package com.example.test.listviewwithimage; 2. 3. import android.support.v7.app.AppCompatActivity; 4. import android.os.Bundle; 5. import android.view.View; 6. import android.widget.AdapterView; 7. import android.widget.ListView; 8. import android.widget.Toast; 9. 10. public class MainActivity extends AppCompatActivity { 11.
ListView list;
12. 13.
String[] maintitle ={
14.
"Title 1","Title 2",
15.
"Title 3","Title 4",
16.
"Title 5",
17.
};
18. 19.
String[] subtitle ={
20.
"Sub Title 1","Sub Title 2",
21.
"Sub Title 3","Sub Title 4",
22. 23.
"Sub Title 5", };
24. 25.
Integer[] imgid={
26.
R.drawable.download_1,R.drawable.download_2,
27.
R.drawable.download_3,R.drawable.download_4,
28.
R.drawable.download_5,
29.
};
30.
@Override
31.
protected void onCreate(Bundle savedInstanceState) {
32.
super.onCreate(savedInstanceState);
33.
setContentView(R.layout.activity_main);
34. 35.
MyListAdapter adapter=new MyListAdapter(this, maintitle, subtitle,imgid);
36.
list=(ListView)findViewById(R.id.list);
37.
list.setAdapter(adapter);
38. 39. 40.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
41. 42. 43.
@Override public void onItemClick(AdapterView> parent, View view,int position, long id) {
44.
// TODO Auto-generated method stub
45.
if(position == 0) {
46.
//code specific to first list item
47.
Toast.makeText(getApplicationContext(),"Place Your First Option Code",Toast. LENGTH_SHORT).show();
48.
}
49. 50.
else if(position == 1) {
51.
//code specific to 2nd list item
52.
Toast.makeText(getApplicationContext(),"Place Your Second Option Code",Toa st.LENGTH_SHORT).show();
53.
}
54. 55. 56.
else if(position == 2) {
57.
Toast.makeText(getApplicationContext(),"Place Your Third Option Code",Toast .LENGTH_SHORT).show();
58.
}
59.
else if(position == 3) {
60. 61.
Toast.makeText(getApplicationContext(),"Place Your Forth Option Code",Toast .LENGTH_SHORT).show();
62.
}
63.
else if(position == 4) {
64. 65.
Toast.makeText(getApplicationContext(),"Place Your Fifth Option Code",Toast. LENGTH_SHORT).show();
66.
}
67. 68.
}
69.
});
70.
}
71. }
Customize Our ListView Create another java class MyListView.java which extends ArrayAdapter class. This class customizes our listview. MyListView.java 1. package com.example.test.listviewwithimage; 2. 3. import android.app.Activity; 4. 5. import android.view.LayoutInflater; 6. import android.view.View; 7. import android.view.ViewGroup; 8. import android.widget.ArrayAdapter; 9. import android.widget.ImageView; 10. import android.widget.TextView; 11. 12. public class MyListAdapter extends ArrayAdapter<String> {
13. 14.
private final Activity context;
15.
private final String[] maintitle;
16.
private final String[] subtitle;
17.
private final Integer[] imgid;
18. 19.
public MyListAdapter(Activity context, String[] maintitle,String[] subtitle, Integer[] imgid ){
20.
super(context, R.layout.mylist, maintitle);
21.
// TODO Auto-generated constructor stub
22. 23.
this.context=context;
24.
this.maintitle=maintitle;
25.
this.subtitle=subtitle;
26.
this.imgid=imgid;
27. 28.
}
29. 30.
public View getView(int position,View view,ViewGroup parent) {
31.
LayoutInflater inflater=context.getLayoutInflater();
32.
View rowView=inflater.inflate(R.layout.mylist, null,true);
33. 34.
TextView titleText = (TextView) rowView.findViewById(R.id.title);
35.
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
36.
TextView subtitleText = (TextView) rowView.findViewById(R.id.subtitle);
37. 38.
titleText.setText(maintitle[position]);
39.
imageView.setImageResource(imgid[position]);
40.
subtitleText.setText(subtitle[position]);
41. 42.
return rowView;
43. 44.
};
45. }
Android RatingBar can be used to get the rating from the user. The Rating returns a floatingpoint number. It may be 2.0, 3.5, 4.0 etc.
Android RatingBar displays the rating in stars. Android RatingBar is the subclass of AbsSeekBar class. The getRating() method of android RatingBar class returns the rating number.
Android RatingBar Example Let's see the simple example of rating bar in android.
activity_main.xml Drag the RatingBar and Button from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
8.
android:id="@+id/ratingBar1"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentTop="true"
12.
android:layout_centerHorizontal="true"
13.
android:layout_marginTop="44dp" />
14. 15.
<Button
16.
android:id="@+id/button1"
17.
android:layout_width="wrap_content"
18.
android:layout_height="wrap_content"
19.
android:layout_alignLeft="@+id/ratingBar1"
20.
android:layout_below="@+id/ratingBar1"
21.
android:layout_marginLeft="92dp"
22.
android:layout_marginTop="66dp"
23.
android:text="submit" />
24. 25.
Activity class Let's write the code to display the rating of the user.
File: MainActivity.java 1. package com.example.rating; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.view.Menu; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.Button; 9. import android.widget.RatingBar; 10. import android.widget.Toast; 11. 12. public class MainActivity extends Activity { 13.
RatingBar ratingbar1;
14.
Button button;
15.
@Override
16.
protected void onCreate(Bundle savedInstanceState) {
17.
super.onCreate(savedInstanceState);
18.
setContentView(R.layout.activity_main);
19.
addListenerOnButtonClick();
20.
}
21. 22.
public void addListenerOnButtonClick(){
23.
ratingbar1=(RatingBar)findViewById(R.id.ratingBar1);
24.
button=(Button)findViewById(R.id.button1);
25.
//Performing action on Button Click
26.
button.setOnClickListener(new OnClickListener(){
27. 28.
@Override
29.
public void onClick(View arg0) {
30.
//Getting the rating and displaying it on the toast
31.
String rating=String.valueOf(ratingbar1.getRating());
32.
Toast.makeText(getApplicationContext(), rating, Toast.LENGTH_LONG).show();
33.
}
34. 35.
});
36.
}
37.
@Override
38.
public boolean onCreateOptionsMenu(Menu menu) {
39.
// Inflate the menu; this adds items to the action bar if it is present.
40.
getMenuInflater().inflate(R.menu.activity_main, menu);
41.
return true;
42.
}
43. 44. } Android WebView is used to display web page in android. The web page can be loaded from same application or URL. It is used to display online content in android activity. Android WebView uses webkit engine to display web page. The android.webkit.WebView is the subclass of AbsoluteLayout class. The loadUrl() and loadData() methods of Android WebView class are used to load and display web page.
Let's see the simple code to display javatpoint.com web page using web view. 1. WebView mywebview = (WebView) findViewById(R.id.webView1); 2. mywebview.loadUrl("http://www.javatpoint.com/"); Let's see the simple code to display HTML web page using web view. In this case, html file must be located inside the asset directory. 1. WebView mywebview = (WebView) findViewById(R.id.webView1); 2. mywebview.loadUrl("file:///android_asset/myresource.html"); Let's see another code to display HTML code of a string. 1. String data = "Hello, Javatpoint!
"; 2. mywebview.loadData(data, "text/html", "UTF-8");
Android WebView Example Let's see a simple example of android webview.
activity_main.xml File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
<WebView
8.
android:id="@+id/webView1"
9.
android:layout_width="match_parent"
10.
android:layout_height="match_parent"
11.
android:layout_alignParentTop="true"
12.
android:layout_centerHorizontal="true"
13.
android:layout_marginTop="42dp" />
14. 15.
Activity class File: MainActivity.java 1. package com.example.webview; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.view.Menu; 6. import android.webkit.WebView; 7. 8. public class MainActivity extends Activity { 9. 10.
@Override
11.
protected void onCreate(Bundle savedInstanceState) {
12.
super.onCreate(savedInstanceState);
13.
setContentView(R.layout.activity_main);
14. 15.
WebView mywebview = (WebView) findViewById(R.id.webView1);
16.
//mywebview.loadUrl("http://www.javatpoint.com/");
17. 18.
/*String data = "Hello, Javatpoint!
";
19.
mywebview.loadData(data, "text/html", "UTF-8"); */
20. 21.
mywebview.loadUrl("file:///android_asset/myresource.html");
22.
}
23. 24.
@Override
25.
public boolean onCreateOptionsMenu(Menu menu) {
26.
// Inflate the menu; this adds items to the action bar if it is present.
27.
getMenuInflater().inflate(R.menu.activity_main, menu);
28.
return true;
29.
}
30. 31. } Android SeekBar is a kind of ProgressBar with draggable thumb. The end user can drag the thum left and right to move the progress of song, file download etc. The SeekBar.OnSeekBarChangeListener interface provides methods to perform even handling for seek bar. Android SeekBar and RatingBar classes are the sub classes of AbsSeekBar.
Android SeekBar Example activity_main.xml Drag the seek bar from the pallete, now activity_main.xml will look like this:
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
android:paddingBottom="@dimen/activity_vertical_margin"
6.
android:paddingLeft="@dimen/activity_horizontal_margin"
7.
android:paddingRight="@dimen/activity_horizontal_margin"
8.
android:paddingTop="@dimen/activity_vertical_margin"
9.
tools:context=".MainActivity" >
10. 11.
<SeekBar
12.
android:id="@+id/seekBar1"
13.
android:layout_width="match_parent"
14.
android:layout_height="wrap_content"
15.
android:layout_alignParentTop="true"
16.
android:layout_centerHorizontal="true"
17.
android:layout_marginTop="39dp" />
18. 19.
Activity class Let's see the Activity class displaying seek bar and performing event handling.
File: MainActivity.java 1. package com.example.seekbar; 2. import android.os.Bundle; 3. import android.app.Activity; 4. import android.view.Menu; 5. import android.widget.SeekBar; 6. import android.widget.SeekBar.OnSeekBarChangeListener; 7. import android.widget.Toast; 8. public class MainActivity extends Activity implements OnSeekBarChangeListener{ 9.
SeekBar seekBar1;
10.
@Override
11.
protected void onCreate(Bundle savedInstanceState) {
12.
super.onCreate(savedInstanceState);
13.
setContentView(R.layout.activity_main);
14. 15.
seekBar1=(SeekBar)findViewById(R.id.seekBar1);
16.
seekBar1.setOnSeekBarChangeListener(this);
17.
}
18.
@Override
19.
public void onProgressChanged(SeekBar seekBar, int progress,
20.
boolean fromUser) {
21.
Toast.makeText(getApplicationContext(),"seekbar progress: "+progress, Toast.LENGT H_SHORT).show();
22.
}
23.
@Override
24.
public void onStartTrackingTouch(SeekBar seekBar) {
25.
Toast.makeText(getApplicationContext(),"seekbar touch started!", Toast.LENGTH_SHO RT).show();
26.
}
27.
@Override
28.
public void onStopTrackingTouch(SeekBar seekBar) {
29.
Toast.makeText(getApplicationContext(),"seekbar touch stopped!", Toast.LENGTH_SH ORT).show();
30.
}
31.
@Override
32.
public boolean onCreateOptionsMenu(Menu menu) {
33.
// Inflate the menu; this adds items to the action bar if it is present.
34.
getMenuInflater().inflate(R.menu.main, menu);
35.
return true;
36.
}
37. }
Android DatePicker Example Android DatePicker is a widget to select date. It allows you to select date by day, month and year. Like DatePicker, android also provides TimePicker to select time. The android.widget.DatePicker is the subclass of FrameLayout class.
Android DatePicker Example Let's see the simple example of datepicker widget in android.
activity_main.xml File: activity_main.xml
1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
8.
android:id="@+id/textView1"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentLeft="true"
12.
android:layout_alignParentTop="true"
13.
android:layout_marginLeft="50dp"
14.
android:layout_marginTop="36dp"
15.
android:text="Current Date:" />
16. 17.
<Button
18.
android:id="@+id/button1"
19.
android:layout_width="wrap_content"
20.
android:layout_height="wrap_content"
21.
android:layout_alignParentBottom="true"
22.
android:layout_centerHorizontal="true"
23.
android:layout_marginBottom="140dp"
24.
android:text="Change Date" />
25. 26.
27.
android:id="@+id/datePicker1"
28.
android:layout_width="wrap_content"
29.
android:layout_height="wrap_content"
30.
android:layout_above="@+id/button1"
31.
android:layout_centerHorizontal="true"
32.
android:layout_marginBottom="30dp" />
33. 34.
Activity class File: MainActivity.java 1. package com.example.datepicker2; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.view.Menu; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.Button; 9. import android.widget.DatePicker; 10. import android.widget.TextView; 11. import android.widget.Toast; 12. 13. public class MainActivity extends Activity { 14.
DatePicker picker;
15.
Button displayDate;
16.
TextView textview1;
17.
@Override
18.
protected void onCreate(Bundle savedInstanceState) {
19.
super.onCreate(savedInstanceState);
20.
setContentView(R.layout.activity_main);
21. 22.
textview1=(TextView)findViewById(R.id.textView1);
23.
picker=(DatePicker)findViewById(R.id.datePicker1);
24.
displayDate=(Button)findViewById(R.id.button1);
25. 26.
textview1.setText(getCurrentDate());
27. 28.
displayDate.setOnClickListener(new OnClickListener(){
29.
@Override
30.
public void onClick(View view) {
31. 32.
textview1.setText(getCurrentDate()); }
33. 34.
});
35.
}
36.
public String getCurrentDate(){
37.
StringBuilder builder=new StringBuilder();
38.
builder.append("Current Date: ");
39.
builder.append((picker.getMonth() + 1)+"/");//month is 0 based
40.
builder.append(picker.getDayOfMonth()+"/");
41.
builder.append(picker.getYear());
42.
return builder.toString();
43.
}
44.
@Override
45.
public boolean onCreateOptionsMenu(Menu menu) {
46.
// Inflate the menu; this adds items to the action bar if it is present.
47.
getMenuInflater().inflate(R.menu.activity_main, menu);
48.
return true;
49.
}
50. 51. }
Android TimePicker widget is used to select date. It allows you to select time by hour and minute. You cannot select time by seconds. The android.widget.TimePicker is the subclass of FrameLayout class.
Android TimePicker Example Let's see a simple example of android time picker.
activity_main.xml File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
<TimePicker
8.
android:id="@+id/timePicker1"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentTop="true"
12.
android:layout_centerHorizontal="true"
13.
android:layout_marginTop="86dp" />
14. 15.
16.
android:id="@+id/textView1"
17.
android:layout_width="wrap_content"
18.
android:layout_height="wrap_content"
19.
android:layout_alignLeft="@+id/timePicker1"
20.
android:layout_alignParentTop="true"
21.
android:layout_marginTop="17dp"
22.
android:text="Current Time:" />
23. 24.
<Button
25.
android:id="@+id/button1"
26.
android:layout_width="wrap_content"
27.
android:layout_height="wrap_content"
28.
android:layout_alignLeft="@+id/timePicker1"
29.
android:layout_below="@+id/timePicker1"
30.
android:layout_marginLeft="37dp"
31.
android:layout_marginTop="55dp"
32.
android:text="Change Time" />
33. 34.
Activity class File: MainActivity.java 1. package com.example.timepicker1; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.view.Menu; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.Button; 9. import android.widget.TextView;
10. import android.widget.TimePicker; 11. import android.widget.Toast; 12. 13. public class MainActivity extends Activity { 14.
TextView textview1;
15.
TimePicker timepicker1;
16.
Button changetime;
17. 18.
@Override
19.
protected void onCreate(Bundle savedInstanceState) {
20.
super.onCreate(savedInstanceState);
21.
setContentView(R.layout.activity_main);
22. 23.
textview1=(TextView)findViewById(R.id.textView1);
24.
timepicker1=(TimePicker)findViewById(R.id.timePicker1);
25.
//Uncomment the below line of code for 24 hour view
26.
timepicker1.setIs24HourView(true);
27.
changetime=(Button)findViewById(R.id.button1);
28. 29.
textview1.setText(getCurrentTime());
30. 31.
changetime.setOnClickListener(new OnClickListener(){
32.
@Override
33.
public void onClick(View view) {
34.
textview1.setText(getCurrentTime());
35.
}
36.
});
37. 38.
}
39. 40.
public String getCurrentTime(){
41.
String currentTime="Current Time: "+timepicker1.getCurrentHour()+":"+timepicker1. getCurrentMinute();
42.
return currentTime;
43.
}
44.
@Override
45.
public boolean onCreateOptionsMenu(Menu menu) {
46.
// Inflate the menu; this adds items to the action bar if it is present.
47.
getMenuInflater().inflate(R.menu.activity_main, menu);
48.
return true;
49.
}
50. 51. }
android.widget.AnalogClock and android.widget.DigitalClock classes provides the functionality to display analog and digital clocks. Android analog and digital clocks are used to show time in android application. Android AnalogClock is the subclass of View class. Android DigitalClock is the subclass of TextView class. Since Android API level 17, it is deprecated. You are recommended to use TextClock Instead.
Note: Analog and Digital clocks cannot be used to change the time of the device. To do so, you need to use DatePicker and TimePicker.
In android, you need to drag analog and digital clocks from the pallet to display analog and digital clocks. It represents the timing of the current device.
activity_main.xml Now, drag the analog and digital clocks, now the xml file will look like this.
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
8.
android:id="@+id/analogClock1"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentTop="true"
12.
android:layout_centerHorizontal="true"
13.
android:layout_marginTop="22dp" / rel="nofollow">
14. 15.
16.
android:id="@+id/digitalClock1"
17.
android:layout_width="wrap_content"
18.
android:layout_height="wrap_content"
19.
android:layout_below="@+id/analogClock1"
20.
android:layout_centerHorizontal="true"
21.
android:layout_marginTop="81dp"
22.
android:text="DigitalClock" />
23. 24.
Activity class We have not write any code here.
File: MainActivity.java 1. package com.example.analogdigital; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.view.Menu; 6. 7. public class MainActivity extends Activity { 8. 9.
@Override
10.
protected void onCreate(Bundle savedInstanceState) {
11.
super.onCreate(savedInstanceState);
12.
setContentView(R.layout.activity_main);
13.
}
14. 15.
@Override
16.
public boolean onCreateOptionsMenu(Menu menu) {
17.
// Inflate the menu; this adds items to the action bar if it is present.
18.
getMenuInflater().inflate(R.menu.activity_main, menu);
19.
return true;
20.
}
21. }
android progress bar dialog box to display the status of work being done e.g. downloading file, analyzing status of work etc. In this example, we are displaying the progress dialog for dummy file download operation. Here we are using android.app.ProgressDialog class to show the progress bar. Android ProgressDialog is the subclass of AlertDialog class. The ProgressDialog class provides methods to work on progress bar like setProgress(), setMessage(), setProgressStyle(), setMax(), show() etc. The progress range of Progress Dialog is 0 to 10000. Let's see a simple example to display progress bar in android. 1. ProgressDialog progressBar = new ProgressDialog(this); 2. progressBar.setCancelable(true);//you can cancel it by pressing back button 3. progressBar.setMessage("File downloading ..."); 4. progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 5. progressBar.setProgress(0);//initially progress is 0 6. progressBar.setMax(100);//sets the maximum value 100 7. progressBar.show();//displays the progress bar
Android Progress Bar Example by ProgressDialog Let's see a simple example to create progress bar using ProgressDialog class.
activity_main.xml Drag one button from the pallete, now the activity_main.xml file will look like this:
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
<Button
8.
android:id="@+id/button1"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentTop="true"
12.
android:layout_centerHorizontal="true"
13.
android:layout_marginTop="116dp"
14.
android:text="download file" />
15. 16.
Activity class Let's write the code to display the progress bar dialog box.
File: MainActivity.java 1. package com.example.progressbar1; 2. import android.app.Activity; 3. import android.app.ProgressDialog; 4. import android.os.Bundle; 5. import android.os.Handler; 6. import android.widget.Button; 7. import android.view.Menu; 8. import android.view.View; 9. import android.view.View.OnClickListener; 10. public class MainActivity extends Activity { 11.
Button btnStartProgress;
12.
ProgressDialog progressBar;
13.
private int progressBarStatus = 0;
14.
private Handler progressBarHandler = new Handler();
15.
private long fileSize = 0;
16.
@Override
17.
protected void onCreate(Bundle savedInstanceState) {
18.
super.onCreate(savedInstanceState);
19.
setContentView(R.layout.activity_main);
20.
addListenerOnButtonClick();
21.
}
22.
public void addListenerOnButtonClick() {
23.
btnStartProgress = (Button) findViewById(R.id.button1);
24.
btnStartProgress.setOnClickListener(new OnClickListener(){
25. 26.
@Override
27.
public void onClick(View v) {
28.
// creating progress bar dialog
29.
progressBar = new ProgressDialog(v.getContext());
30.
progressBar.setCancelable(true);
31.
progressBar.setMessage("File downloading ...");
32.
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
33.
progressBar.setProgress(0);
34.
progressBar.setMax(100);
35.
progressBar.show();
36.
//reset progress bar and filesize status
37.
progressBarStatus = 0;
38.
fileSize = 0;
39. 40. 41. 42.
new Thread(new Runnable() { public void run() { while (progressBarStatus < 100) {
43.
// performing operation
44.
progressBarStatus = doOperation();
45.
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
46.
// Updating the progress bar
47.
progressBarHandler.post(new Runnable() {
48.
public void run() {
49.
progressBar.setProgress(progressBarStatus);
50.
}
51.
});
52.
}
53.
// performing operation if file is downloaded,
54.
if (progressBarStatus >= 100) {
55.
// sleeping for 1 second after operation completed
56.
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace ();}
57.
// close the progress bar dialog
58.
progressBar.dismiss();
59.
}
60.
}
61.
}).start();
62.
}//end of onClick method
63.
});
64.
}
65.
// checking how much file is downloaded and updating the filesize
66.
public int doOperation() {
67.
//The range of ProgressDialog starts from 0 to 10000
68.
while (fileSize <= 10000) {
69.
fileSize++;
70.
if (fileSize == 1000) {
71.
return 10;
72.
} else if (fileSize == 2000) {
73.
return 20;
74.
} else if (fileSize == 3000) {
75.
return 30;
76.
} else if (fileSize == 4000) {
77.
return 40;//you can add more else if
78.
} else{
79.
return 100;
80.
}
81.
}//end of while
82.
return 100;
83.
}//end of doOperation
84. 85.
@Override
86.
public boolean onCreateOptionsMenu(Menu menu) {
87.
// Inflate the menu; this adds items to the action bar if it is present.
88.
getMenuInflater().inflate(R.menu.main, menu);
89.
return true;
90. 91. }
}
Android ScrollView (Vertical) The android.widget.ScrollView class provides the functionality of scroll view. ScrollView is used to scroll the child elements of palette inside ScrollView. Android supports vertical scroll view as default scroll view. Vertical ScrollView scrolls elements vertically. Android uses HorizontalScrollView for horizontal ScrollView. Let's implement simple example of vertical ScrollView.
activity_main.xml Now, drag ScrollView from palette to activity_main.xml file and place some palette element inside it. File: activity_main.xml 1. 2.
xmlns:tools="http://schemas.android.com/tools"
4.
android:layout_width="match_parent"
5.
android:layout_height="match_parent"
6.
android:paddingBottom="@dimen/activity_vertical_margin"
7.
android:paddingLeft="@dimen/activity_horizontal_margin"
8.
android:paddingRight="@dimen/activity_horizontal_margin"
9.
android:paddingTop="@dimen/activity_vertical_margin"
10.
tools:context="com.example.test.scrollviews.MainActivity">
11. 12. 13.
14.
android:layout_width="wrap_content"
15.
android:layout_height="wrap_content"
16.
android:textAppearance="?android:attr/textAppearanceMedium"
17.
android:text="Vertical ScrollView example"
18.
android:id="@+id/textView"
19.
android:layout_gravity="center_horizontal"
20.
android:layout_centerHorizontal="true"
21.
android:layout_alignParentTop="true" />
22. 23.
24.
<ScrollView android:layout_marginTop="30dp"
25.
android:layout_width="fill_parent"
26.
android:layout_height="wrap_content"
27.
android:id="@+id/scrollView">
28. 29. 30.
31.
android:layout_width="fill_parent"
32.
android:layout_height="fill_parent"
33.
android:orientation="vertical" >
34. 35.
<Button
36.
android:layout_width="fill_parent"
37.
android:layout_height="wrap_content"
38.
android:text="Button 1" />
39.
<Button
40.
android:layout_width="fill_parent"
41.
android:layout_height="wrap_content"
42.
android:text="Button 2" />
43.
<Button
44.
android:layout_width="fill_parent"
45.
android:layout_height="wrap_content"
46.
android:text="Button 3" />
47.
<Button
48.
android:layout_width="fill_parent"
49.
android:layout_height="wrap_content"
50.
android:text="Button 4" />
51.
<Button
52.
android:layout_width="fill_parent"
53.
android:layout_height="wrap_content"
54.
android:text="Button 5" />
55.
<Button
56.
android:layout_width="fill_parent"
57.
android:layout_height="wrap_content"
58.
android:text="Button 6" />
59. 60.
<Button android:layout_width="fill_parent"
61.
android:layout_height="wrap_content"
62.
android:text="Button 7" />
63.
<Button
64.
android:layout_width="fill_parent"
65.
android:layout_height="wrap_content"
66.
android:text="Button 8" />
67.
<Button
68.
android:layout_width="fill_parent"
69.
android:layout_height="wrap_content"
70.
android:text="Button 9" />
71.
<Button
72.
android:layout_width="fill_parent"
73.
android:layout_height="wrap_content"
74.
android:text="Button 10" />
75.
<Button
76.
android:layout_width="fill_parent"
77.
android:layout_height="wrap_content"
78.
android:text="Button 11" />
79.
<Button
80.
android:layout_width="fill_parent"
81.
android:layout_height="wrap_content"
82.
android:text="Button 12" />
83.
<Button
84.
android:layout_width="fill_parent"
85.
android:layout_height="wrap_content"
86.
android:text="Button 13" />
87.
<Button
88.
android:layout_width="fill_parent"
89.
android:layout_height="wrap_content"
90.
android:text="Button 14" />
91.
<Button
92.
android:layout_width="fill_parent"
93.
android:layout_height="wrap_content"
94.
android:text="Button 15" />
95.
<Button
96.
android:layout_width="fill_parent"
97.
android:layout_height="wrap_content"
98.
android:text="Button 16" />
99.
<Button
100.
android:layout_width="fill_parent"
101.
android:layout_height="wrap_content"
102.
android:text="Button 17" />
103.
<Button
104.
android:layout_width="fill_parent"
105.
android:layout_height="wrap_content"
106.
android:text="Button 18" />
107. 108.
<Button
109.
android:layout_width="fill_parent"
110.
android:layout_height="wrap_content"
111.
android:text="Button 19" />
112.
<Button
113.
android:layout_width="fill_parent"
114.
android:layout_height="wrap_content"
115.
android:text="Button 20" />
116. 117.
118. 119.
120. 121.
Activity class In activity class, we have not changed any code. File: MainActivity.java 1. package com.example.test.scrollviews; 2. 3. import android.support.v7.app.AppCompatActivity; 4. import android.os.Bundle; 5. 6. public class MainActivity extends AppCompatActivity { 7. 8.
@Override
9.
protected void onCreate(Bundle savedInstanceState) {
10.
super.onCreate(savedInstanceState);
11.
setContentView(R.layout.activity_main);
12.
}
13. }
Android HorizontalScrollView A HorizontalScrollView is a FrameLayout. The android.widget.HorizontalScrollView class provides the functionality of horizontal scroll view. HorizontalScrollView is used to scroll the child elements or views in a horizontal direction. HorizontalScrollView only supports horizontal scrolling. For vertical scroll, android uses ScrollView. Let's implement simple example of HorizontalScrollView.
activity_main.xml Now, drag HorizontalScrollView from palette to activity_main.xml file and place some views or elements inside it. 1. 2.
android:layout_width="fill_parent"
4.
android:layout_height="fill_parent">
5. 6. 7.
8.
android:layout_width="wrap_content"
9.
android:layout_height="wrap_content"
10.
android:textAppearance="?android:attr/textAppearanceSmall"
11.
android:text="Horizontal ScrollView Example"
12.
android:id="@+id/textView"
13.
android:layout_alignParentTop="true"
14.
android:layout_centerHorizontal="true" />
15. 16.
17.
18.
android:layout_width="match_parent"
19.
android:layout_height="match_parent"
20.
android:layout_marginTop="25dp">
21.
22.
android:layout_width="match_parent"
23.
android:layout_height="60dp"
24.
android:id="@+id/horizontalScrollView">
25. 26.
27.
android:layout_width="wrap_content"
28.
android:layout_height="wrap_content"
29.
android:orientation="horizontal">
30.
<Button
31.
android:layout_width="wrap_content"
32.
android:layout_height="wrap_content"
33.
android:text="New Button1"
34.
android:id="@+id/button1" />
35.
<Button
36.
android:layout_width="wrap_content"
37.
android:layout_height="wrap_content"
38.
android:text="New Button2"
39.
android:id="@+id/button2" />
40. 41.
<Button
42.
android:layout_width="wrap_content"
43.
android:layout_height="wrap_content"
44.
android:text="New Button3"
45.
android:id="@+id/button3" />
46.
<Button
47.
android:layout_width="wrap_content"
48.
android:layout_height="wrap_content"
49.
android:text="New Button4"
50.
android:id="@+id/button4" />
51.
<Button
52.
android:layout_width="wrap_content"
53.
android:layout_height="wrap_content"
54.
android:text="New Button5"
55.
android:id="@+id/button5" />
56.
<Button
57.
android:layout_width="wrap_content"
58.
android:layout_height="wrap_content"
59.
android:text="New Button6"
60.
android:id="@+id/button6" />
61.
<Button
62.
android:layout_width="wrap_content"
63.
android:layout_height="wrap_content"
64.
android:text="New Button7"
65.
android:id="@+id/button7" />
66.
<Button
67.
android:layout_width="wrap_content"
68.
android:layout_height="wrap_content"
69.
android:text="New Button8"
70.
android:id="@+id/button8"/>
71.
72. 73. 74.
75.
Activity class This is auto generated code, we have not written any code here. File: MainActivity.java 1. package com.example.test.horizantalscrollview; 2. 3. import android.support.v7.app.AppCompatActivity; 4. import android.os.Bundle; 5. 6. public class MainActivity extends AppCompatActivity { 7. 8.
@Override
9.
protected void onCreate(Bundle savedInstanceState) {
10.
super.onCreate(savedInstanceState);
11.
setContentView(R.layout.activity_main);
12.
}
13. }
Android Image Switcher Android image switcher provides an animation over images to transition from one image to another. In order to use image switcher, we need to implement ImageSwitcher component in .xml file. The setFactory() method of ImageSwitcher provide implementation of ViewFactory interface. ViewFactory interface implements its unimplemented method and returns an ImageView.
Example of Image Switcher Let's implement an image switcher. Create activity_main.xml and content_main.xml file in layout folder. Place some images in drawable folder which are to be switch.
activity_main.xml File: activity_main.xml 1. 2.
xmlns:app="http://schemas.android.com/apk/res-auto"
4.
xmlns:tools="http://schemas.android.com/tools"
5.
android:layout_width="match_parent"
6.
android:layout_height="match_parent"
7.
android:fitsSystemWindows="true"
8.
tools:context="com.example.test.imageswitcher.MainActivity" rel="nofollow">
9. 10.
11.
android:layout_width="match_parent"
12.
android:layout_height="wrap_content"
13.
android:theme="@style/AppTheme.AppBarOverlay" rel="nofollow">
14. 15. 16.
17.
android:layout_width="match_parent"
18.
android:layout_height="?attr/actionBarSize"
19.
android:background="?attr/colorPrimary"
20.
app:popupTheme="@style/AppTheme.PopupOverlay" / rel="nofollow">
21. 22.
23.
24. 25.
content_main.xml File: content_main.xml 1. 2.
xmlns:app="http://schemas.android.com/apk/res-auto"
4.
xmlns:tools="http://schemas.android.com/tools"
5.
android:layout_width="match_parent"
6.
android:layout_height="match_parent"
7.
android:paddingBottom="@dimen/activity_vertical_margin"
8.
android:paddingLeft="@dimen/activity_horizontal_margin"
9.
android:paddingRight="@dimen/activity_horizontal_margin"
10.
android:paddingTop="@dimen/activity_vertical_margin"
11.
app:layout_behavior="@string/appbar_scrolling_view_behavior"
12.
tools:context="com.example.test.imageswitcher.MainActivity"
13.
tools:showIn="@layout/activity_main">
14. 15.
16.
android:layout_width="wrap_content"
17.
android:layout_height="wrap_content"
18.
android:text="Image Switcher Example"
19. 20.
android:id="@+id/textView"
21.
android:layout_alignParentTop="true"
22.
android:layout_centerHorizontal="true" />
23. 24. 25.
26.
android:layout_width="match_parent"
27.
android:layout_height="250dp"
28.
android:layout_marginBottom="28dp"
29.
android:layout_marginTop="40dp" />
30. 31.
<Button
32.
android:layout_width="wrap_content"
33.
android:layout_height="wrap_content"
34.
android:text="Next"
35.
android:id="@+id/button"
36.
android:layout_marginBottom="47dp"
37.
android:layout_alignParentBottom="true"
38.
android:layout_centerHorizontal="true" />
39.
Activity class File: MainActivity.java 1. package com.example.test.imageswitcher; 2. 3. import android.os.Bundle; 4. import android.support.v7.app.AppCompatActivity; 5. import android.support.v7.widget.Toolbar; 6. import android.view.View; 7. import android.widget.Button; 8. import android.widget.ImageSwitcher; 9. import android.widget.ImageView; 10. import android.widget.ViewSwitcher; 11. 12. import android.app.ActionBar; 13. import android.view.animation.Animation; 14. import android.view.animation.AnimationUtils; 15. 16. 17. public class MainActivity extends AppCompatActivity { 18.
ImageSwitcher imageSwitcher;
19.
Button nextButton;
20.
21. 22.
int imageSwitcherImages[] = {R.drawable.cpp, R.drawable.c_sarp, R.drawable.jsp, R.drawable.mysql, R.drawable.ha doop};
23. 24.
int switcherImageLength = imageSwitcherImages.length;
25.
int counter = -1;
26. 27.
@Override
28.
protected void onCreate(Bundle savedInstanceState) {
29.
super.onCreate(savedInstanceState);
30.
setContentView(R.layout.activity_main);
31.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
32.
setSupportActionBar(toolbar);
33. 34.
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
35.
nextButton = (Button) findViewById(R.id.button);
36. 37.
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
38.
@Override
39.
public View makeView() {
40.
ImageView switcherImageView = new ImageView(getApplicationContext());
41.
switcherImageView.setLayoutParams(new ImageSwitcher.LayoutParams(
42.
ActionBar.LayoutParams.FILL_PARENT, ActionBar.LayoutParams.FILL_PARENT
43.
));
44.
switcherImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
45.
switcherImageView.setImageResource(R.drawable.hadoop);
46.
//switcherImageView.setMaxHeight(100);
47.
return switcherImageView;
48. 49.
} });
50. 51. 52. aniOut = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right); 53.
Animation aniIn = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
54. 55.
imageSwitcher.setOutAnimation(aniOut);
56.
imageSwitcher.setInAnimation(aniIn);
57. 58.
nextButton.setOnClickListener(new View.OnClickListener() {
59.
@Override
60.
public void onClick(View v) {
61.
counter++;
62.
if (counter == switcherImageLength){
63.
counter = 0;
64.
imageSwitcher.setImageResource(imageSwitcherImages[counter]);
65.
}
66.
else{
67.
imageSwitcher.setImageResource(imageSwitcherImages[counter]);
68.
}
69.
}
70.
});
71.
}
72. 73. }
Android Image Slider Android image slider slides one entire screen to another screen. Image slider is created by ViewPager which is provided by support library. To implement image slider, you need to inherit ViewPager class which extends PagerAdapter.
Example of Image Slider Let's see an example of android image slider.
activity_main.xml In activity_main.xml file, we have wrapped ViewPager inside RelativeLayout. File: activity_main.xml 1. 2.
xmlns:tools="http://schemas.android.com/tools"
4.
android:layout_width="fill_parent"
5.
android:layout_height="fill_parent"
6.
android:paddingBottom="@dimen/activity_vertical_margin"
7.
android:paddingLeft="@dimen/activity_horizontal_margin"
8.
android:paddingRight="@dimen/activity_horizontal_margin"
9.
android:paddingTop="@dimen/activity_vertical_margin"
10.
tools:context="com.example.test.imageslider.MainActivity">
11. 12. 13.
14.
android:id="@+id/viewPage"
15.
android:layout_width="fill_parent"
16.
android:layout_height="fill_parent" / rel="nofollow">
17. 18.
Activity class File: MainActivity.java 1. package com.example.test.imageslider; 2. 3. import android.support.v4.view.ViewPager; 4. import android.support.v7.app.AppCompatActivity; 5. import android.os.Bundle; 6. 7. public class MainActivity extends AppCompatActivity { 8. 9.
@Override
10.
protected void onCreate(Bundle savedInstanceState) {
11.
super.onCreate(savedInstanceState);
12.
setContentView(R.layout.activity_main);
13. 14.
ViewPager mViewPager = (ViewPager) findViewById(R.id.viewPage);
15.
ImageAdapter adapterView = new ImageAdapter(this);
16.
mViewPager.setAdapter(adapterView);
17. 18. }
}
ImageAdapter class Now create ImageAdapter class which extends PagerAdapter for android image slider. Place some images in drawable folder which are to be slid. File: ImageAdapter.java 1. package com.example.test.imageslider; 2. 3. import android.content.Context; 4. import android.support.v4.view.PagerAdapter; 5. import android.support.v4.view.ViewPager; 6. import android.view.View; 7. import android.view.ViewGroup; 8. import android.widget.ImageView; 9. 10. public class ImageAdapter extends PagerAdapter{ 11.
Context mContext;
12. 13.
ImageAdapter(Context context) {
14. 15.
this.mContext = context; }
16. 17.
@Override
18.
public boolean isViewFromObject(View view, Object object) {
19. 20.
return view == ((ImageView) object); }
21. 22.
private int[] sliderImageId = new int[]{
23.
R.drawable.image1, R.drawable.image2, R.drawable.image3,R.drawable.image4, R. drawable.image5,
24.
};
25. 26.
@Override
27.
public Object instantiateItem(ViewGroup container, int position) {
28.
ImageView imageView = new ImageView(mContext);
29.
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
30.
imageView.setImageResource(sliderImageId[position]);
31.
((ViewPager) container).addView(imageView, 0);
32.
return imageView;
33.
}
34. 35.
@Override
36.
public void destroyItem(ViewGroup container, int position, Object object) {
37.
((ViewPager) container).removeView((ImageView) object);
38.
}
39. 40.
@Override
41.
public int getCount() {
42.
return sliderImageId.length;
43.
}
44. } We need to override following methods of PagerAdapter class. 1. isViewFromObject(View, Object): This method checks the view whether it is associated with key and returned by instantiateItem(). 2. instantiateItem(ViewGroup, int): This method creates the page position passed as an argument. 3. destroyItem(ViewGroup, int, Object): It removes the page from its current position from container. In this example we simply removed
object using
removeView(). 4. getCount(): It returns the number of available views in ViewPager.
Android ViewStub A ViewStub is a zero-sized invisible View which is used to load "layout resource" at runtime. ViewStub is a zero dimension View, so you will not see anything on the layout pallete. To make parent resource visible, inflate() method is invoked. To make ViewStub visible or invisible, setVisibility(int) method is invoked. The View.VISIBLE constant is used for making ViewStub visible and View.GONE constant is used for invisible.
Example of ViewStub Let's create an example of ViewStub View that displays and hides an ImageView (image) created in another layout (my_layout.xml) file.
File: activity.xml 1. 2.
xmlns:tools="http://schemas.android.com/tools"
4.
android:layout_width="match_parent"
5.
android:layout_height="match_parent"
6.
android:paddingBottom="@dimen/activity_vertical_margin"
7.
android:paddingLeft="@dimen/activity_horizontal_margin"
8.
android:paddingRight="@dimen/activity_horizontal_margin"
9.
android:paddingTop="@dimen/activity_vertical_margin"
10.
tools:context="com.example.test.viewstubexample.MainActivity">
11. 12.
13.
android:layout_width="wrap_content"
14.
android:layout_height="wrap_content"
15.
android:id="@+id/viewStub"
16.
android:layout_marginLeft="120dp"
17.
android:layout="@layout/my_layout"
18.
android:layout_alignParentTop="true" />
19. 20.
<Button
21.
android:layout_width="wrap_content"
22.
android:layout_height="wrap_content"
23.
android:text="Show"
24.
android:id="@+id/show"
25.
android:layout_alignParentBottom="true"
26.
android:layout_alignParentLeft="true"
27.
android:layout_alignParentStart="true"
28.
android:layout_marginLeft="65dp"
29.
android:layout_marginStart="65dp" />
30. 31.
<Button
32.
android:layout_width="wrap_content"
33.
android:layout_height="wrap_content"
34.
android:text="Hide"
35.
android:id="@+id/hide"
36.
android:layout_alignParentBottom="true"
37.
android:layout_toRightOf="@+id/show"
38.
android:layout_toEndOf="@+id/show"
39.
android:layout_marginLeft="51dp"
40.
android:layout_marginStart="51dp" />
41. 42. File: my_layout.xml 1. 2.
android:layout_width="match_parent"
4.
android:layout_height="match_parent">
5. 6.
7.
android:layout_width="wrap_content"
8.
android:layout_height="wrap_content"
9.
android:id="@+id/imageView"
10.
android:background="@drawable/image"
11.
/>
12. 13. File: MainActivity.java 1. package com.example.test.viewstubexample; 2. 3. import android.support.v7.app.AppCompatActivity; 4. import android.os.Bundle; 5. import android.view.View; 6. import android.view.ViewStub; 7. import android.widget.Button; 8. 9. public class MainActivity extends AppCompatActivity { 10.
ViewStub viewStub;
11.
Button show,hide;
12.
@Override
13.
protected void onCreate(Bundle savedInstanceState) {
14.
super.onCreate(savedInstanceState);
15.
setContentView(R.layout.activity_main);
16. 17.
show=(Button)findViewById(R.id.show);
18.
hide=(Button)findViewById(R.id.hide);
19.
viewStub=(ViewStub)findViewById(R.id.viewStub);
20.
viewStub.inflate();
21. 22.
show.setOnClickListener(new View.OnClickListener() {
23.
@Override
24.
public void onClick(View v) {
25.
viewStub.setVisibility(View.VISIBLE);
26.
}
27.
});
28.
hide.setOnClickListener(new View.OnClickListener() {
29.
@Override
30.
public void onClick(View v) {
31.
viewStub.setVisibility(View.GONE);
32.
}
33.
});
34.
}
35. }
Android TabLayout TabLayout is used to implement horizontal tabs. TabLayout is released by Android after the deprecation of ActionBar.TabListener (API level 21). TabLayout is introduced in design support library to implement tabs. Tabs are created using newTab() method of TabLayout class. The title and icon of Tabs are set through setText(int) and setIcon(int)methods of TabListener interface respectively. Tabs of layout are attached over TabLayout using the method addTab(Tab) method. 1. TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout); 2. tabLayout.addTab(tabLayout.newTab().setText("Tab 1")); 3. tabLayout.addTab(tabLayout.newTab().setText("Tab 2")); 4. tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
We can also add tab item to TabLayout using TabItem of android design widget. 1.
android:text="@string/tab_text"/ rel="nofollow">
Example of TabLayout using ViewPager Let's create an example of TabLayout using ViewPager and Fragment. File: activity.xml Create an activity.xml file with TabLayout and ViewPager view components. 1. 2.
xmlns:app="http://schemas.android.com/apk/res-auto"
4.
xmlns:tools="http://schemas.android.com/tools"
5.
android:layout_width="match_parent"
6.
android:layout_height="match_parent"
7.
tools:context="tablayout.example.com.tablayout.MainActivity" rel="nofollow">
8. 9. 10.
11.
android:id="@+id/tabLayout"
12.
android:layout_width="match_parent"
13.
android:layout_height="wrap_content"
14.
android:background="#1db995" rel="nofollow">
15.
16. 17.
18.
android:id="@+id/viewPager"
19.
android:layout_width="355dp"
20.
android:layout_height="455dp"
21.
app:layout_constraintTop_toBottomOf="@+id/tabLayout"
22.
tools:layout_editor_absoluteX="8dp" / rel="nofollow">
23. 24. 25.
File: build.gradle Now gave the dependency library of TabLayout in build.gradle file. 1. implementation 'com.android.support:design:26.1.0' File: MainActivity.java In this file, we implement two additional listener addOnPageChangeListener(listener) of ViewPager which makes slides the different fragments of tabs and addOnTabSelectedListener(listener) of TabLayout which select the current tab on tab selection. 1. package tablayout.example.com.tablayout; 2. 3. import android.support.design.widget.TabLayout; 4. import android.support.v4.view.ViewPager; 5. import android.support.v7.app.AppCompatActivity; 6. import android.os.Bundle; 7. 8. public class MainActivity extends AppCompatActivity { 9.
TabLayout tabLayout;
10.
ViewPager viewPager;
11.
@Override
12.
protected void onCreate(Bundle savedInstanceState) {
13.
super.onCreate(savedInstanceState);
14.
setContentView(R.layout.activity_main);
15. 16.
tabLayout=(TabLayout)findViewById(R.id.tabLayout);
17.
viewPager=(ViewPager)findViewById(R.id.viewPager);
18. 19.
tabLayout.addTab(tabLayout.newTab().setText("Home"));
20.
tabLayout.addTab(tabLayout.newTab().setText("Sport"));
21.
tabLayout.addTab(tabLayout.newTab().setText("Movie"));
22.
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
23. 24.
final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(), tabL ayout.getTabCount());
25. 26.
viewPager.setAdapter(adapter);
27.
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListen er(tabLayout));
28. 29.
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
30.
@Override
31.
public void onTabSelected(TabLayout.Tab tab) {
32.
viewPager.setCurrentItem(tab.getPosition());
33.
}
34. 35.
@Override
36.
public void onTabUnselected(TabLayout.Tab tab) {
37. 38.
}
39. 40.
@Override
41.
public void onTabReselected(TabLayout.Tab tab) {
42. 43.
}
44.
});
45. 46.
}
47. } File: MyAdapter.java 1. package tablayout.example.com.tablayout; 2. 3. import android.content.Context; 4. import android.support.v4.app.Fragment; 5. import android.support.v4.app.FragmentPagerAdapter; 6. import android.support.v4.app.FragmentManager; 7. 8. public class MyAdapter extends FragmentPagerAdapter { 9. 10.
private Context myContext;
11.
int totalTabs;
12. 13.
public MyAdapter(Context context, FragmentManager fm, int totalTabs) {
14.
super(fm);
15.
myContext = context;
16.
this.totalTabs = totalTabs;
17.
}
18. 19.
// this is for fragment tabs
20.
@Override
21.
public Fragment getItem(int position) {
22.
switch (position) {
23.
case 0:
24.
HomeFragment homeFragment = new HomeFragment();
25.
return homeFragment;
26.
case 1:
27.
SportFragment sportFragment = new SportFragment();
28.
return sportFragment;
29.
case 2:
30.
MovieFragment movieFragment = new MovieFragment();
31.
return movieFragment;
32.
default:
33.
return null;
34.
}
35.
}
36. // this counts total number of tabs 37.
@Override
38.
public int getCount() {
39.
return totalTabs;
40.
}
41. } Now create different fragment files for all different tabs. File: HomeFragment.java 1. package tablayout.example.com.tablayout; 2. 3. import android.os.Bundle; 4. import android.support.v4.app.Fragment; 5. import android.view.LayoutInflater;
6. import android.view.View; 7. import android.view.ViewGroup; 8. 9. public class HomeFragment extends Fragment { 10. 11. 12.
public HomeFragment() {
// Required empty public constructor
13. 14.
}
15. 16.
@Override
17.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
18.
Bundle savedInstanceState) {
19.
// Inflate the layout for this fragment
20.
return inflater.inflate(R.layout.fragment_home, container, false);
21.
}
22. 23. } File: fragment_home.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context="tablayout.example.com.tablayout.HomeFragment">
6. 7.
8. 9.
10.
android:layout_width="match_parent"
11.
android:layout_height="match_parent"
12.
android:gravity="center"
13.
android:text="@string/home_fragment" />
14. 15. File: SportFragment.java
1. package tablayout.example.com.tablayout; 2. 3. import android.os.Bundle; 4. import android.support.v4.app.Fragment; 5. import android.view.LayoutInflater; 6. import android.view.View; 7. import android.view.ViewGroup; 8. 9. public class SportFragment extends Fragment { 10. 11. 12.
public SportFragment() {
// Required empty public constructor
13. 14.
}
15. 16.
@Override
17.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
18.
Bundle savedInstanceState) {
19.
// Inflate the layout for this fragment
20.
return inflater.inflate(R.layout.fragment_sport, container, false);
21.
}
22. 23. } File: fragment_sport.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context="tablayout.example.com.tablayout.SportFragment">
6. 7.
8.
9.
android:layout_width="match_parent"
10.
android:layout_height="match_parent"
11.
android:gravity="center"
12.
android:text="@string/sport_fragment" />
13. 14. File: MovieFragment.java 1. package tablayout.example.com.tablayout; 2. 3. import android.os.Bundle; 4. import android.support.v4.app.Fragment; 5. import android.view.LayoutInflater; 6. import android.view.View; 7. import android.view.ViewGroup; 8. 9. public class MovieFragment extends Fragment { 10. 11. 12.
public MovieFragment() {
// Required empty public constructor
13. 14.
}
15. 16.
@Override
17.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
18.
Bundle savedInstanceState) {
19.
// Inflate the layout for this fragment
20.
return inflater.inflate(R.layout.fragment_movie, container, false);
21.
}
22. 23. } File: fragment_movie.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context="tablayout.example.com.tablayout.MovieFragment">
6. 7.
8.
9.
android:layout_width="match_parent"
10.
android:layout_height="match_parent"
11.
android:gravity="center"
12.
android:text="@string/movie_fragment" />
13. 14. File: strings.xml 1. 2.
<string name="app_name">TabLayout
3. 4.
5.
<string name="home_fragment">Home Fragment
6.
<string name="sport_fragment">Sport Fragment
7.
<string name="movie_fragment">Movie Fragment
8. 9.
Android SearchView Android SearchView provides user interface to search query submitted over search provider. SearchView widget can be implemented over ToolBar/ActionBar or inside a layout. SearchView is by default collapsible and set to be iconified using setIconifiedByDefault(true) method of SearchView class. For making search field visible, SearchView uses setIconifiedByDefault(false) method.
Methods of SearchView 1. public boolean onQueryTextSubmit(String query): It searches the query on the submission of content over SearchView editor. It is case dependent. 2. public boolean onQueryTextChange(String newText): It searches the query at the time of text change over SearchView editor.
Example of SearchView Let's see the example of SearchView over layout, searching data in a ListView.
activity_main.xml Create an activity_main.xml file in layout folder containing ScrollView and ListView. File: activity_main.xml 1. 2.
xmlns:tools="http://schemas.android.com/tools"
4.
android:layout_width="match_parent"
5.
android:layout_height="match_parent"
6.
android:paddingBottom="@dimen/activity_vertical_margin"
7.
android:paddingLeft="@dimen/activity_horizontal_margin"
8.
android:paddingRight="@dimen/activity_horizontal_margin"
9.
android:paddingTop="@dimen/activity_vertical_margin"
10.
tools:context="com.example.test.searchview.MainActivity">
11. 12.
13.
android:layout_width="match_parent"
14.
android:layout_height="match_parent"
15.
android:id="@+id/lv1"
16.
android:divider="#ad5"
17.
android:dividerHeight="2dp"
18.
android:layout_below="@+id/searchView"/>
19. 20.
<SearchView
21.
android:id="@+id/searchView"
22.
android:layout_width="wrap_content"
23.
android:layout_height="wrap_content"
24.
android:queryHint="Search Here"
25.
android:iconifiedByDefault="false"
26.
android:layout_alignParentTop="true"
27.
/>
28. 29.
Activity class File: MainActivity.java
1. package com.example.test.searchview; 2. 3. import android.support.v7.app.AppCompatActivity; 4. import android.os.Bundle; 5. import android.widget.ArrayAdapter; 6. import android.widget.Filter; 7. import android.widget.ListView; 8. import android.widget.SearchView; 9. import android.widget.Toast; 10. 11. import java.util.ArrayList; 12. 13. public class MainActivity extends AppCompatActivity { 14.
SearchView searchView;
15.
ListView listView;
16.
ArrayList<String> list;
17.
ArrayAdapter<String > adapter;
18.
@Override
19.
protected void onCreate(Bundle savedInstanceState) {
20.
super.onCreate(savedInstanceState);
21.
setContentView(R.layout.activity_main);
22. 23.
searchView = (SearchView) findViewById(R.id.searchView);
24.
listView = (ListView) findViewById(R.id.lv1);
25. 26.
list = new ArrayList<>();
27.
list.add("Apple");
28.
list.add("Banana");
29.
list.add("Pineapple");
30.
list.add("Orange");
31.
list.add("Lychee");
32.
list.add("Gavava");
33.
list.add("Peech");
34.
list.add("Melon");
35.
list.add("Watermelon");
36.
list.add("Papaya");
37.
38.
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
39.
listView.setAdapter(adapter);
40. 41.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
42.
@Override
43.
public boolean onQueryTextSubmit(String query) {
44. 45.
if(list.contains(query)){
46.
adapter.getFilter().filter(query);
47.
}else{
48.
Toast.makeText(MainActivity.this, "No Match found",Toast.LENGTH_LONG).sh ow();
49.
}
50.
return false;
51.
}
52. 53.
@Override
54.
public boolean onQueryTextChange(String newText) {
55.
//
56.
adapter.getFilter().filter(newText); return false;
57.
}
58.
});
59.
}
60. }
Android SearchView on ToolBar As we have already implemented SearchView widget over activity layout, it can also be implemented over ToolBar/ActionBar. For implementing SearchView over ToolBar, we need to create menu option and place SearchView widget on it.
Example of SearchView on ToolBar (ActionBar) Let's us see the example of SearchView over ToolBar and searching data in ListView.
Directory Structure of this Example activity_main.xml Create an activity_main.xml file in layout folder containing ListView. File: activity_main.xml 1. 2.
xmlns:app="http://schemas.android.com/apk/res-auto"
4.
xmlns:tools="http://schemas.android.com/tools"
5.
android:layout_width="match_parent"
6.
android:layout_height="match_parent"
7.
tools:context="searchview.toolbar.com.searchviewtoolbar.MainActivity" rel="nofollow">
8. 9.
10.
android:id="@+id/listView"
11.
android:layout_width="match_parent"
12.
android:layout_height="fill_parent"
13.
/>
14. 15.
menu.xml Create a menu.xml file in menu folder and place the following code. This code places the SearchView widget over ToolBar. File: menu.xml 1. 2. <menu xmlns:app="http://schemas.android.com/apk/res-auto" 3. xmlns:android="http://schemas.android.com/apk/res/android"> 4. 5.
android:id="@+id/app_bar_search"
7.
android:icon="@drawable/ic_search_black_24dp"
8.
android:title="Search"
9.
app:showAsAction="ifRoom|withText"
10.
app:actionViewClass="android.widget.SearchView"/>
11.
Activity class File: MainActivity.java 1. package searchview.toolbar.com.searchviewtoolbar; 2. 3. import android.support.v4.view.MenuItemCompat; 4. import android.support.v7.app.AppCompatActivity; 5. import android.os.Bundle; 6. import android.view.Menu; 7. import android.view.MenuInflater; 8. import android.view.MenuItem; 9. import android.widget.ArrayAdapter; 10. import android.widget.ListView; 11. import android.widget.SearchView; 12. import android.widget.Toast; 13. 14. import java.util.ArrayList; 15. 16. public class MainActivity extends AppCompatActivity { 17. 18.
ListView listView;
19.
ArrayList<String> list;
20.
ArrayAdapter<String > adapter;
21.
@Override
22.
protected void onCreate(Bundle savedInstanceState) {
23.
super.onCreate(savedInstanceState);
24.
setContentView(R.layout.activity_main);
25. 26.
listView = (ListView) findViewById(R.id.listView);
27. 28.
list = new ArrayList<>();
29.
list.add("Apple");
30.
list.add("Banana");
31.
list.add("Pineapple");
32.
list.add("Orange");
33.
list.add("Lychee");
34.
list.add("Gavava");
35.
list.add("Peech");
36.
list.add("Melon");
37.
list.add("Watermelon");
38.
list.add("Papaya");
39. 40.
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
41.
listView.setAdapter(adapter);
42.
}
43. 44.
@Override
45.
public boolean onCreateOptionsMenu(Menu menu) {
46.
MenuInflater inflater = getMenuInflater();
47.
inflater.inflate(R.menu.menu, menu);
48.
MenuItem searchViewItem = menu.findItem(R.id.app_bar_search);
49.
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(search ViewItem);
50.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
51.
@Override
52.
public boolean onQueryTextSubmit(String query) {
53. 54.
searchView.clearFocus();
/*
if(list.contains(query)){ adapter.getFilter().filter(query);
55.
}else{
56.
Toast.makeText(MainActivity.this, "No Match found",Toast.LENGTH_L
57.
ONG).show(); }*/
58. 59.
return false;
60. 61.
}
62. 63.
@Override
64.
public boolean onQueryTextChange(String newText) {
65.
adapter.getFilter().filter(newText);
66.
return false;
67.
}
68.
});
69.
return super.onCreateOptionsMenu(menu);
70.
}
71. }
Android EditText with TextWatcher (Searching data from ListView) Android EditText is a subclass of TextView. EditText is used for entering and modifying text. While using EditText width, we must specify its input type in inputType property of EditText which configures the keyboard according to input. EditText uses TextWatcher interface to watch change made over EditText. For doing this, EditText calls the addTextChangedListener() method.
Methods of TextWatcher 1. beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3): It is executed before making any change over EditText. 2. onTextChanged(CharSequence cs, int arg1, int arg2, int arg3): It is executed while making any change over EditText. 3. afterTextChanged(Editable arg0): It is executed after change made over EditText.
Example of EditText with TextWatcher() In this example, we will implement EditText with TextWatcher to search data from ListView.
activity_main.xml Create an activity_main.xml file in layout folder containing EditText and ListView. File: activity_main.xml 1. 2.
xmlns:tools="http://schemas.android.com/tools"
4.
android:layout_width="match_parent"
5.
android:layout_height="match_parent"
6.
android:paddingBottom="@dimen/activity_vertical_margin"
7.
android:paddingLeft="@dimen/activity_horizontal_margin"
8.
android:paddingRight="@dimen/activity_horizontal_margin"
9.
android:paddingTop="@dimen/activity_vertical_margin"
10.
tools:context="com.example.test.searchfromlistview.MainActivity">
11. 12.
<EditText
13.
android:layout_width="wrap_content"
14.
android:layout_height="wrap_content"
15.
android:id="@+id/editText"
16.
android:inputType="text"
17.
android:layout_alignParentTop="true"
18.
android:layout_alignParentLeft="true"
19.
android:layout_alignParentStart="true"
20.
android:layout_alignParentRight="true"
21.
android:layout_alignParentEnd="true" />
22. 23.
24.
android:layout_width="wrap_content"
25.
android:layout_height="wrap_content"
26.
android:id="@+id/listView"
27.
android:layout_below="@+id/editText"
28.
android:layout_alignParentLeft="true"
29.
android:layout_alignParentStart="true" />
30. Create another file list_item.xml in layout folder which contains data of ListView.
list_item.xm File: list_item.xml 1. 2.
xmlns:android="http://schemas.android.com/apk/res/android"
4.
android:orientation="vertical"
5.
android:layout_width="match_parent"
6.
android:layout_height="match_parent">
7. 8.
android:layout_width="fill_parent"
10.
android:layout_height="wrap_content"
11.
android:padding="10dip"
12.
android:textSize="16dip"
13.
android:textStyle="bold"/>
14.
Activity class Activity class 1. package com.example.test.searchfromlistview; 2. 3. import android.os.Bundle; 4. import android.text.Editable; 5. import android.text.TextWatcher; 6. import android.widget.ArrayAdapter; 7. import android.widget.EditText; 8. import android.widget.ListView; 9. import android.support.v7.app.AppCompatActivity; 10. import android.widget.Toast; 11. 12. public class MainActivity extends AppCompatActivity { 13. 14.
private ListView lv;
15.
private EditText editText;
16.
private ArrayAdapter<String> adapter;
17. 18. 19.
private String products[] = {"Apple", "Banana","Pinapple", "Orange", "Papaya", "Melon", "Grapes", "Water Melon","Lychee", "Guava", "Mango", "Kivi"};
20.
@Override
21.
protected void onCreate(Bundle savedInstanceState) {
22.
super.onCreate(savedInstanceState);
23.
setContentView(R.layout.activity_main);
24. 25.
lv = (ListView) findViewById(R.id.listView);
26.
editText = (EditText) findViewById(R.id.editText);
27.
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, pr oducts);
28.
lv.setAdapter(adapter);
29. 30.
editText.addTextChangedListener(new TextWatcher() {
31. 32.
@Override
33.
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
34.
adapter.getFilter().filter(cs);
35.
}
36.
@Override
37. 38.
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
39.
Toast.makeText(getApplicationContext(),"before text change",Toast.LENGTH_LO NG).show();
40.
}
41. 42.
@Override
43.
public void afterTextChanged(Editable arg0) {
44.
Toast.makeText(getApplicationContext(),"after text change",Toast.LENGTH_LON G).show();
45.
}
46.
});
47.
}
48. }
Android Activity Lifecycle Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android Activity is the subclass of ContextThemeWrapper class. An activity is the single screen in android. It is like window or frame of Java. By the help of activity, you can place all your UI components or widgets in a single screen. The 7 lifecycle method of Activity describes how activity will behave at different states.
Android Activity Lifecycle methods Let's see the 7 lifecycle methods of android activity.
Method
Description
onCreate
called when activity is first created.
onStart
called when activity is becoming visible to the user.
onResume
called when activity will start interacting with the user.
onPause
called when activity is not visible to the user.
onStop
called when activity is no longer visible to the user.
onRestart
called after your activity is stopped, prior to start.
onDestroy
called before the activity is destroyed.
Android Activity Lifecycle Example It provides the details about the invocation of life cycle methods of activity. In this example, we are displaying the content on the logcat.
File: MainActivity.java 1. package com.example.activitylifecycle; 2. import android.os.Bundle; 3. import android.app.Activity; 4. import android.util.Log; 5. import android.view.Menu; 6. public class MainActivity extends Activity { 7.
@Override
8.
protected void onCreate(Bundle savedInstanceState) {
9.
super.onCreate(savedInstanceState);
10.
setContentView(R.layout.activity_main);
11.
Log.d("lifecycle","onCreate invoked");
12.
}
13.
@Override
14.
protected void onStart() {
15.
super.onStart();
16.
Log.d("lifecycle","onStart invoked");
17.
}
18.
@Override
19.
protected void onResume() {
20.
super.onResume();
21.
Log.d("lifecycle","onResume invoked");
22.
}
23.
@Override
24.
protected void onPause() {
25.
super.onPause();
26.
Log.d("lifecycle","onPause invoked");
27.
}
28.
@Override
29.
protected void onStop() {
30.
super.onStop();
31. 32.
Log.d("lifecycle","onStop invoked"); }
33. 34.
@Override protected void onRestart() {
35.
super.onRestart();
36.
Log.d("lifecycle","onRestart invoked");
37.
}
38.
@Override
39.
protected void onDestroy() {
40.
super.onDestroy();
41. 42. 43. }
Log.d("lifecycle","onDestroy invoked"); }
Android Intent Tutorial Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services etc. It is generally used with startActivity() method to invoke activity, broadcast receivers etc. The dictionary meaning of intent is intention or purpose. So, it can be described as the intention to do action. The LabeledIntent is the subclass of android.content.Intent class. Android intents are mainly used to: o
Start the service
o
Launch an activity
o
Display a web page
o
Display a list of contacts
o
Broadcast a message
o
Dial a phone call etc.
Types of Android Intents There are two types of intents in android: implicit and explicit.
1) Implicit Intent Implicit Intent doesn't specifiy the component. In such case, intent provides information of available components provided by the system that is to be invoked. For example, you may write the following code to view the webpage. 1. Intent intent=new Intent(Intent.ACTION_VIEW); 2. intent.setData(Uri.parse("http://www.javatpoint.com")); 3. startActivity(intent);
2) Explicit Intent Explicit Intent specifies the component. In such case, intent provides the external class to be invoked. 1. Intent i = new Intent(getApplicationContext(), ActivityTwo.class); 2. startActivity(i); To get the full code of explicit intent, visit the next page.
Android Implicit Intent Example Let's see the simple example of implicit intent that displays a web page.
activity_main.xml File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6.
<EditText
7.
android:id="@+id/editText1"
8.
android:layout_width="wrap_content"
9.
android:layout_height="wrap_content"
10.
android:layout_alignParentTop="true"
11.
android:layout_centerHorizontal="true"
12.
android:layout_marginTop="44dp"
13.
android:ems="10" />
14.
<Button
15.
android:id="@+id/button1"
16.
android:layout_width="wrap_content"
17.
android:layout_height="wrap_content"
18.
android:layout_below="@+id/editText1"
19.
android:layout_centerHorizontal="true"
20.
android:layout_marginTop="54dp"
21.
android:text="Visit" />
22.
Activity class File: MainActivity.java 1. package org.sssit.implicitintent; 2. import android.net.Uri; 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.content.Intent; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.Button; 9. import android.widget.EditText; 10. public class MainActivity extends Activity { 11.
@Override
12.
protected void onCreate(Bundle savedInstanceState) {
13.
super.onCreate(savedInstanceState);
14.
setContentView(R.layout.activity_main);
15.
final EditText editText1=(EditText)findViewById(R.id.editText1);
16.
Button button1=(Button)findViewById(R.id.button1);
17.
button1.setOnClickListener(new OnClickListener() {
18.
@Override
19.
public void onClick(View arg0) {
20.
String url=editText1.getText().toString();
21.
Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
22.
startActivity(intent);
23.
}
24.
});
25.
}
26. }
Android Explicit Intent Example Android Explicit intent specifies the component to be invoked from activity. In other words, we can call another activity in android by explicit intent. We can also pass the information from one activity to another using explicit intent.
Here, we are going to see an example to call one activity from another and vice-versa.
Android calling one activity from another activity example Let's see the simple example of android explicit example that calls one activity from another and vice versa.
activity_main.xml File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
<Button
8.
android:id="@+id/Button01"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentLeft="true"
12.
android:layout_below="@+id/TextView01"
13.
android:layout_marginLeft="65dp"
14.
android:layout_marginTop="38dp"
15.
android:onClick="onClick"
16.
android:text="Call second activity" />
17. 18.
19.
android:id="@+id/TextView01"
20.
android:layout_width="wrap_content"
21.
android:layout_height="wrap_content"
22.
android:layout_alignLeft="@+id/Button01"
23.
android:layout_alignParentTop="true"
24.
android:layout_marginLeft="18dp"
25.
android:layout_marginTop="27dp"
26.
android:minHeight="60dip"
27.
android:text="First Activity"
28.
android:textSize="20sp" />
29. 30.
activitytwo_main.xml File: activitytwo_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
tools:context=".MainActivity" >
6. 7.
<Button
8.
android:id="@+id/Button01"
9.
android:layout_width="wrap_content"
10.
android:layout_height="wrap_content"
11.
android:layout_alignParentLeft="true"
12.
android:layout_below="@+id/TextView01"
13.
android:layout_marginLeft="65dp"
14.
android:layout_marginTop="38dp"
15.
android:onClick="onClick"
16.
android:text="Call First activity" />
17. 18.
19.
android:id="@+id/TextView01"
20.
android:layout_width="wrap_content"
21.
android:layout_height="wrap_content"
22.
android:layout_alignLeft="@+id/Button01"
23.
android:layout_alignParentTop="true"
24.
android:layout_marginLeft="18dp"
25.
android:layout_marginTop="27dp"
26.
android:minHeight="60dip"
27.
android:text="Second Activity"
28.
android:textSize="20sp" />
29. 30.
ActivityOne class File: MainActivityOne.java
1. package com.example.explicitintent2; 2. import android.os.Bundle; 3. import android.app.Activity; 4. import android.content.Intent; 5. import android.view.Menu; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.Button; 9. import android.widget.Toast; 10. public class ActivityOne extends Activity { 11.
/** Called when the activity is first created. */
12.
@Override
13.
public void onCreate(Bundle savedInstanceState) {
14.
super.onCreate(savedInstanceState);
15.
setContentView(R.layout.activity_main);
16.
Button button1=(Button)findViewById(R.id.Button01);
17. 18.
button1.setOnClickListener(new OnClickListener(){
19.
public void onClick(View view) {
20.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
21.
i.putExtra("Value1", "Android By Javatpoint");
22.
i.putExtra("Value2", "Simple Tutorial");
23.
// Set the request code to any code you like, you can identify the
24.
// callback via this code
25.
startActivity(i);
26.
}
27.
});
28. 29.
} }
ActivityTwo class File: MainActivityTwo.java 1. package com.example.explicitintent2; 2. import android.app.Activity; 3. import android.content.Intent; 4. import android.os.Bundle; 5. import android.view.View; 6. import android.view.View.OnClickListener;
7. import android.widget.Button; 8. import android.widget.EditText; 9. import android.widget.TextView; 10. import android.widget.Toast; 11. public class ActivityTwo extends Activity { 12. /** Called when the activity is first created. */ 13. @Override 14. public void onCreate(Bundle bundle) { 15.
super.onCreate(bundle);
16.
TextView tv=new TextView(this);
17.
tv.setText("second activity");
18.
setContentView(R.layout.activity_two);
19.
Bundle extras = getIntent().getExtras();
20.
String value1 = extras.getString("Value1");
21.
String value2 = extras.getString("Value2");
22.
Toast.makeText(getApplicationContext(),"Values are:\n First value: "+value1+
"\n Second Value: "+value2,Toast.LENGTH_LONG).show();
23. 24.
Button button1=(Button)findViewById(R.id.Button01);
25.
button1.setOnClickListener(new OnClickListener(){
26.
public void onClick(View view) {
27.
Intent i = new Intent(getApplicationContext(), ActivityOne.class);
28.
startActivity(i);
29.
}
30.
});
31. } 32. }
Android StartActivityForResult Example By the help of android startActivityForResult() method, we can get result from another activity. By the help of android startActivityForResult() method, we can send information from one activity to another and vice-versa. The android startActivityForResult method, requires a result from the second activity (activity to be invoked). In such case, we need to override the onActivityResult method that is invoked automatically when second activity returns result.
Method Signature There are two variants of startActivityForResult() method. 1. public void startActivityForResult (Intent intent, int requestCode) 2. public void startActivityForResult (Intent intent, int requestCode, Bundle options)
Android StartActivityForResult Example Let's see the simple example of android startActivityForResult method.
activity_main.xml Drag one textview and one button from the pallete, now the xml file will look like this.
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
android:paddingBottom="@dimen/activity_vertical_margin"
6.
android:paddingLeft="@dimen/activity_horizontal_margin"
7.
android:paddingRight="@dimen/activity_horizontal_margin"
8.
android:paddingTop="@dimen/activity_vertical_margin"
9.
tools:context=".MainActivity" >
10.
11.
android:id="@+id/textView1"
12.
android:layout_width="wrap_content"
13.
android:layout_height="wrap_content"
14.
android:layout_alignLeft="@+id/button1"
15.
android:layout_alignParentTop="true"
16.
android:layout_marginTop="48dp"
17.
android:text="Default Message" />
18.
<Button
19.
android:id="@+id/button1"
20.
android:layout_width="wrap_content"
21.
android:layout_height="wrap_content"
22.
android:layout_below="@+id/textView1"
23.
android:layout_centerHorizontal="true"
24.
android:layout_marginTop="42dp"
25.
android:text="GetMessage" />
26.
second_main.xml This xml file is created automatically when you create another activity. To create new activity Right click on the package inside the src -> New -> Other ->Android Activity. Now drag one editText, one textView and one button from the pallete, now the xml file will look like this:
File: second_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
android:paddingBottom="@dimen/activity_vertical_margin"
6.
android:paddingLeft="@dimen/activity_horizontal_margin"
7.
android:paddingRight="@dimen/activity_horizontal_margin"
8.
android:paddingTop="@dimen/activity_vertical_margin"
9.
tools:context=".SecondActivity" >
10.
<EditText
11.
android:id="@+id/editText1"
12.
android:layout_width="wrap_content"
13.
android:layout_height="wrap_content"
14.
android:layout_alignParentTop="true"
15.
android:layout_marginTop="61dp"
16.
android:layout_toRightOf="@+id/textView1"
17.
android:ems="10" />
18.
19.
android:id="@+id/textView1"
20.
android:layout_width="wrap_content"
21.
android:layout_height="wrap_content"
22.
android:layout_alignBaseline="@+id/editText1"
23.
android:layout_alignBottom="@+id/editText1"
24.
android:layout_alignParentLeft="true"
25.
android:text="Enter Message:" />
26.
<Button
27.
android:id="@+id/button1"
28.
android:layout_width="wrap_content"
29.
android:layout_height="wrap_content"
30.
android:layout_below="@+id/editText1"
31.
android:layout_centerHorizontal="true"
32.
android:layout_marginTop="34dp"
33.
android:text="Submit" />
34.
Activity class Now let's write the code that invokes another activity and get result from that activity.
File: MainActivity.java 1. package com.javatpoint.startactivityforresult; 2. import android.os.Bundle; 3. import android.app.Activity; 4. import android.content.Intent; 5. import android.view.Menu; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.Button; 9. import android.widget.TextView; 10. public class MainActivity extends Activity { 11.
TextView textView1;
12.
Button button1;
13.
@Override
14.
protected void onCreate(Bundle savedInstanceState) {
15.
super.onCreate(savedInstanceState);
16.
setContentView(R.layout.activity_main);
17.
textView1=(TextView)findViewById(R.id.textView1);
18.
button1=(Button)findViewById(R.id.button1);
19.
button1.setOnClickListener(new OnClickListener() {
20.
@Override
21.
public void onClick(View arg0) {
22.
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
23. 24.
}
25.
});
26.
}
27. // Call Back method to get the Message form other Activity 28.
@Override
29.
protected void onActivityResult(int requestCode, int resultCode, Intent data)
30.
{
31.
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
32. 33.
if(requestCode==2)
34.
{
35.
String message=data.getStringExtra("MESSAGE");
36.
textView1.setText(message);
37.
}
38.
}
39.
@Override
40.
public boolean onCreateOptionsMenu(Menu menu) {
41.
// Inflate the menu; this adds items to the action bar if it is present.
42.
getMenuInflater().inflate(R.menu.main, menu);
43.
return true;
44.
}
45. }
SecondActivity class Let's write the code that displays the content of second activity layout file.
File: SecondActivity.java 1. package com.javatpoint.startactivityforresult; 2. import android.os.Bundle; 3. import android.app.Activity; 4. import android.content.Intent; 5. import android.view.Menu; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.Button; 9. import android.widget.EditText;
10. import android.widget.TextView; 11. public class SecondActivity extends Activity { 12.
EditText editText1;
13.
Button button1;
14.
@Override
15.
protected void onCreate(Bundle savedInstanceState) {
16.
super.onCreate(savedInstanceState);
17.
setContentView(R.layout.activity_second);
18.
editText1=(EditText)findViewById(R.id.editText1);
19.
button1=(Button)findViewById(R.id.button1);
20.
button1.setOnClickListener(new OnClickListener() {
21.
@Override
22.
public void onClick(View arg0) {
23.
String message=editText1.getText().toString();
24.
Intent intent=new Intent();
25.
intent.putExtra("MESSAGE",message);
26.
setResult(2,intent);
27.
finish();//finishing activity
28.
}
29.
});
30.
}
31.
@Override
32.
public boolean onCreateOptionsMenu(Menu menu) {
33.
// Inflate the menu; this adds items to the action bar if it is present.
34.
getMenuInflater().inflate(R.menu.second, menu);
35.
return true;
36.
}
37. }
Android Share App Data (ACTION_SEND) Android uses ACTION_SEND event of android.content.Intent class to send data from one activity to another and from current activity to outside the application. Intent class needs to specify the data and its type which is to be share.
Most commonly, ACTION_SEND action sends URL of build-in Browser app. While sharing the data, Intent call createChooser()method which takes Intent object and specify the title of the chooser dialog. Intent.createChooser() method allows to display the chooser.
Example of ACTION_SEND In this example, we are going to share plain text which is a URL of browser. activity_main.xml File: activity_main.xml 1. 2.
xmlns:tools="http://schemas.android.com/tools"
4.
android:layout_width="match_parent"
5.
android:layout_height="match_parent"
6.
android:paddingBottom="@dimen/activity_vertical_margin"
7.
android:paddingLeft="@dimen/activity_horizontal_margin"
8.
android:paddingRight="@dimen/activity_horizontal_margin"
9.
android:paddingTop="@dimen/activity_vertical_margin"
10.
tools:context="com.example.test.shareapp.MainActivity">
11. 12.
13.
android:layout_width="wrap_content"
14.
android:layout_height="wrap_content"
15.
android:text="Hello World!"
16.
android:id="@+id/textView" />
17. 18.
<Button
19.
android:layout_width="wrap_content"
20.
android:layout_height="wrap_content"
21.
android:text="Share App"
22.
android:id="@+id/button"
23.
android:layout_marginBottom="95dp"
24.
android:layout_alignParentBottom="true"
25.
android:layout_centerHorizontal="true" />
26. 27.
Activity class File: MainActivity.java 1. package com.example.test.shareapp; 2. 3. import android.content.Intent; 4. import android.support.v7.app.AppCompatActivity; 5. import android.os.Bundle; 6. import android.view.View; 7. import android.widget.Button; 8. 9. public class MainActivity extends AppCompatActivity { 10. Button sharebutton; 11.
@Override
12.
protected void onCreate(Bundle savedInstanceState) {
13.
super.onCreate(savedInstanceState);
14.
setContentView(R.layout.activity_main);
15. 16.
sharebutton=(Button)findViewById(R.id.button);
17.
sharebutton.setOnClickListener(new View.OnClickListener() {
18.
@Override
19.
public void onClick(View v) {
20.
Intent shareIntent =
new Intent(android.content.Intent.ACTION_SEND);
21.
shareIntent.setType("text/plain");
22.
shareIntent.putExtra(Intent.EXTRA_SUBJECT,"Insert Subject here");
23.
String app_url = " https://play.google.com/store/apps/details?id=my.example.ja vatpoint";
24.
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,app_url);
25.
startActivity(Intent.createChooser(shareIntent, "Share via"));
26.
}
27. 28. 29. }
}); }
Android Fragments Android Fragment is the part of activity, it is also known as sub-activity. There can be more than one fragment in an activity. Fragments represent multiple screen inside one activity. Android fragment lifecycle is affected by activity lifecycle because fragments are included in activity. Each fragment has its own life cycle methods that is affected by activity life cycle because fragments are embedded in activity. The FragmentManager class is responsible to make interaction between fragment objects.
Android Fragment Lifecycle The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods for fragment.
No.
Method
Description
1)
onAttach(Activity)
it is called only once when it is attached with
2)
onCreate(Bundle)
It is used to initialize the fragment.
3)
onCreateView(LayoutInflater,
ViewGroup,
creates and returns view hierarchy.
Bundle)
4)
onActivityCreated(Bundle)
It is invoked after the completion of onCreate
5)
onViewStateRestored(Bundle)
It provides information to the fragment that all the saved state of fragment view hierarchy has been restored.
6)
onStart()
makes the fragment visible.
7)
onResume()
makes the fragment interactive.
8)
onPause()
is called when fragment is no longer interactive.
9)
onStop()
is called when fragment is no longer visible.
10)
onDestroyView()
allows the fragment to clean up resources.
11)
onDestroy()
allows the fragment to do final clean up of fra
12)
onDetach()
It is called immediately prior to the fragm associated with its activity.
Android Fragment Example Let's have a look at the simple example of android fragment.
activity_main.xml File: activity_main.xml 1.
android:layout_width="fill_parent"
3.
android:layout_height="fill_parent" >
4. 5.
6.
android:id="@+id/fragment2"
7.
android:name="com.example.fragmentexample.Fragment2"
8.
android:layout_width="0px"
9.
android:layout_height="match_parent"
10.
android:layout_weight="1"
11.
/>
12. 13.
14.
android:id="@+id/fragment1"
15.
android:name="com.example.fragmentexample.Fragment1"
16.
android:layout_width="0px"
17.
android:layout_height="match_parent"
18.
android:layout_weight="1"
19.
/>
20. 21.
File: fragment1.xml 1. 2.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
android:orientation="vertical"
6.
android:background="#00ff00"
7.
>
8. 9.
10.
android:id="@+id/textView1"
11.
android:layout_width="wrap_content"
12.
android:layout_height="wrap_content"
13.
android:text="fra0067ment frist"
14.
android:textAppearance="?android:attr/textAppearanceLarge" />
15. 16.
File: fragment2.xml 1. 2.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
android:orientation="vertical"
6.
android:background="#0000ff"
7.
>
8. 9.
10.
android:id="@+id/textView1"
11.
android:layout_width="wrap_content"
12.
android:layout_height="wrap_content"
13.
android:text="Second Fragment"
14.
android:textAppearance="?android:attr/textAppearanceLarge" />
15.
16.
MainActivity class File: MainActivity.java 1. package com.example.fragmentexample; 2. 3. import android.os.Bundle; 4. import android.app.Activity; 5. import android.view.Menu; 6. public class MainActivity extends Activity { 7. 8.
@Override
9.
protected void onCreate(Bundle savedInstanceState) {
10.
super.onCreate(savedInstanceState);
11.
setContentView(R.layout.activity_main);
12.
}
13. }
File: Fragment1.java 1. package com.example.fragmentexample; 2. 3. import android.app.Fragment; 4. import android.os.Bundle; 5. import android.view.LayoutInflater; 6. import android.view.View; 7. import android.view.ViewGroup; 8. 9. public class Fragment1 extends Fragment { 10.
@Override
11.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
12.
Bundle savedInstanceState) {
13.
// TODO Auto-generated method stub
14.
return inflater.inflate(R.layout.fragment1,container, false);
15. 16. 17. }
}
File: Fragment2.java 1. package com.example.fragmentexample; 2. 3. import android.app.Fragment; 4. import android.os.Bundle; 5. import android.view.LayoutInflater; 6. import android.view.View; 7. import android.view.ViewGroup; 8. 9. public class Fragment2 extends Fragment { 10. 11.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
12.
Bundle savedInstanceState) {
13.
// TODO Auto-generated method stub
14.
return inflater.inflate(R.layout.fragment2,container, false);
15.
}
16. 17. }
Android Context Menu Example Android context menu appears when user press long click on the element. It is also known as floating menu. It doesn't support item shortcuts and icons.
Android Context Menu Example Let's see the simple example of context menu in android.
activity_main.xml Drag one listview from the pallete, now the xml file will look like this:
File: activity_main.xml 1.
2.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
android:paddingBottom="@dimen/activity_vertical_margin"
6.
android:paddingLeft="@dimen/activity_horizontal_margin"
7.
android:paddingRight="@dimen/activity_horizontal_margin"
8.
android:paddingTop="@dimen/activity_vertical_margin"
9.
tools:context=".MainActivity" >
10. 11.
12.
android:id="@+id/listView1"
13.
android:layout_width="match_parent"
14.
android:layout_height="wrap_content"
15.
android:layout_alignParentLeft="true"
16.
android:layout_alignParentTop="true"
17.
android:layout_marginLeft="66dp"
18.
android:layout_marginTop="53dp" >
19.
20. 21.
Activity class Let's write the code to display the context menu on press of the listview.
File: MainActivity.java 1. package com.javatpoint.contextmenu; 2. import android.os.Bundle; 3. import android.app.Activity; 4. import android.view.ContextMenu; 5. import android.view.ContextMenu.ContextMenuInfo; 6. import android.view.Menu; 7. import android.view.MenuItem; 8. import android.view.View; 9. import android.widget.AdapterView; 10. import android.widget.ArrayAdapter; 11. import android.widget.ListView;
12. import android.widget.Toast; 13. public class MainActivity extends Activity { 14.
ListView listView1;
15.
String contacts[]={"Ajay","Sachin","Sumit","Tarun","Yogesh"};
16.
@Override
17.
protected void onCreate(Bundle savedInstanceState) {
18.
super.onCreate(savedInstanceState);
19.
setContentView(R.layout.activity_main);
20.
listView1=(ListView)findViewById(R.id.listView1);
21.
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.sim ple_list_item_1,contacts);
22.
listView1.setAdapter(adapter);
23.
// Register the ListView for Context menu
24.
registerForContextMenu(listView1);
25.
}
26.
@Override
27.
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuI nfo)
28.
{
29.
super.onCreateContextMenu(menu, v, menuInfo);
30.
menu.setHeaderTitle("Select The Action");
31.
menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title
32.
menu.add(0, v.getId(), 0, "SMS");
33.
}
34.
@Override
35.
public boolean onContextItemSelected(MenuItem item){
36.
if(item.getTitle()=="Call"){
37.
Toast.makeText(getApplicationContext(),"calling code",Toast.LENGTH_LONG).sh ow();
38.
}
39.
else if(item.getTitle()=="SMS"){
40.
Toast.makeText(getApplicationContext(),"sending sms code",Toast.LENGTH_LON G).show();
41.
}else{
42. 43. 44.
return false; } return true;
45. 46.
} }
Android Popup Menu Example Android Popup Menu displays the menu below the anchor text if space is available otherwise above the anchor text. It disappears if you click outside the popup menu. The android.widget.PopupMenu is the direct subclass of java.lang.Object class.
Android Popup Menu Example Let's see how to create popup menu in android.
activity_main.xml It contains only one button.
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
android:paddingBottom="@dimen/activity_vertical_margin"
6.
android:paddingLeft="@dimen/activity_horizontal_margin"
7.
android:paddingRight="@dimen/activity_horizontal_margin"
8.
android:paddingTop="@dimen/activity_vertical_margin"
9.
tools:context=".MainActivity" >
10. 11.
<Button
12.
android:id="@+id/button1"
13.
android:layout_width="wrap_content"
14.
android:layout_height="wrap_content"
15.
android:layout_alignParentLeft="true"
16.
android:layout_alignParentTop="true"
17.
android:layout_marginLeft="62dp"
18.
android:layout_marginTop="50dp"
19.
android:text="Show Popup" />
20. 21.
popup_menu.xml It contains three items as show below. It is created inside the res/menu directory.
File: poupup_menu.xml 1. <menu xmlns:androclass="http://schemas.android.com/apk/res/android" > 2. 3.
4.
android:id="@+id/one"
5.
android:title="One"/>
6. 7.
8.
android:id="@+id/two"
9.
android:title="Two"/>
10. 11.
12.
android:id="@+id/three"
13.
android:title="Three"/>
14. 15.
Activity class It displays the popup menu on button click.
File: MainActivity.java 1. package com.javatpoint.popupmenu; 2. import android.os.Bundle; 3. import android.app.Activity; 4. import android.view.Menu; 5. import android.view.MenuItem; 6. import android.view.View; 7. import android.view.View.OnClickListener; 8. import android.widget.Button; 9. import android.widget.PopupMenu; 10. import android.widget.Toast; 11. public class MainActivity extends Activity { 12. Button button1;
13. 14.
@Override
15.
protected void onCreate(Bundle savedInstanceState) {
16.
super.onCreate(savedInstanceState);
17.
setContentView(R.layout.activity_main);
18. 19.
button1 = (Button) findViewById(R.id.button1);
20.
button1.setOnClickListener(new OnClickListener() {
21. 22.
@Override
23.
public void onClick(View v) {
24.
//Creating the instance of PopupMenu
25.
PopupMenu popup = new PopupMenu(MainActivity.this, button1);
26.
//Inflating the Popup using xml file
27.
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
28. 29.
//registering popup with OnMenuItemClickListener
30.
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
31.
public boolean onMenuItemClick(MenuItem item) {
32.
Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(),Toast.LENGTH _SHORT).show();
33.
return true;
34.
}
35.
});
36. 37.
popup.show();//showing popup menu
38.
}
39.
});//closing the setOnClickListener method
40. 41.
} }
Android Service Tutorial Android service is a component that is used to perform operations on the background such as playing music, handle network transactions, interacting content providers etc. It doesn't has any UI (user interface).
The service runs in the background indefinitely even if application is destroyed. Moreover, service can be bounded by a component to perform interactivity and inter process communication (IPC). The android.app.Service is subclass of ContextWrapper class.
Note: Android service is not a thread or sepa
process.
Life Cycle of Android Service There can be two forms of a service.The lifecycle of service can follow two different paths: started or bound. 1. Started 2. Bound
1) Started Service A service is started when component (like activity) calls startService() method, now it runs in the background indefinitely. It is stopped by stopService() method. The service can stop itself by calling the stopSelf() method.
2) Bound Service A service is bound when another component (e.g. client) calls bindService() method. The client can unbind the service by calling the unbindService() method. The service cannot be stopped until all clients unbind the service.
Understanding Started and Bound Service by background music example Suppose, I want to play music in the background, so call startService() method. But I want to get information of the current song being played, I will bind the service that provides information about the current song.
Android Service Example Let's see the example of service in android that plays an audio in the background. Audio will not be stopped even if you switch to another activity. To stop the audio, you need to stop the service.
activity_main.xml Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:
File: activity_main.xml 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
android:paddingBottom="@dimen/activity_vertical_margin"
6.
android:paddingLeft="@dimen/activity_horizontal_margin"
7.
android:paddingRight="@dimen/activity_horizontal_margin"
8.
android:paddingTop="@dimen/activity_vertical_margin"
9.
tools:context=".MainActivity" >
10. 11.
<Button
12.
android:id="@+id/buttonStart"
13.
android:layout_width="wrap_content"
14.
android:layout_height="wrap_content"
15.
android:layout_alignParentTop="true"
16.
android:layout_centerHorizontal="true"
17.
android:layout_marginTop="19dp"
18.
android:text="Start Service" />
19. 20.
<Button
21.
android:id="@+id/buttonStop"
22.
android:layout_width="wrap_content"
23.
android:layout_height="wrap_content"
24.
android:layout_above="@+id/buttonNext"
25.
android:layout_alignRight="@+id/buttonStart"
26.
android:layout_marginBottom="35dp"
27.
android:text="Stop Service" />
28. 29.
<Button
30.
android:id="@+id/buttonNext"
31.
android:layout_width="wrap_content"
32.
android:layout_height="wrap_content"
33.
android:layout_alignLeft="@+id/buttonStop"
34.
android:layout_centerVertical="true"
35.
android:text="Next Page" />
36. 37.
activity_next.xml It is the layout file of next activity.
File: activity_next.xml It contains only one textview displaying the message Next Page 1.
xmlns:tools="http://schemas.android.com/tools"
3.
android:layout_width="match_parent"
4.
android:layout_height="match_parent"
5.
android:paddingBottom="@dimen/activity_vertical_margin"
6.
android:paddingLeft="@dimen/activity_horizontal_margin"
7.
android:paddingRight="@dimen/activity_horizontal_margin"
8.
android:paddingTop="@dimen/activity_vertical_margin"
9.
tools:context=".MainActivity" >
10. 11.
12.
android:id="@+id/textView1"
13.
android:layout_width="wrap_content"
14.
android:layout_height="wrap_content"
15.
android:layout_alignParentLeft="true"
16.
android:layout_alignParentTop="true"
17.
android:layout_marginLeft="96dp"
18.
android:layout_marginTop="112dp"
19.
android:text="Next Page" />
20. 21.
Service class Now create the service implemenation class by inheriting the Service class and overridding its callback methods.
File: MyService.java 1. package com.example.serviceexampleaudio; 2. 3. import android.app.Service; 4. import android.content.Intent; 5. import android.media.MediaPlayer; 6. import android.os.IBinder; 7. import android.widget.Toast; 8. public class MyService extends Service { 9.
MediaPlayer myPlayer;
10. @Override 11. public IBinder onBind(Intent intent) { 12. return null; 13. } 14. @Override 15. public void onCreate() { 16. Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show(); 17. 18. myPlayer = MediaPlayer.create(this, R.raw.sun); 19. myPlayer.setLooping(false); // Set looping 20. } 21. @Override 22. public void onStart(Intent intent, int startid) { 23. Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); 24. myPlayer.start(); 25. } 26. @Override 27. public void onDestroy() { 28. Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
29. myPlayer.stop(); 30. } 31. }
Activity class Now create the MainActivity class to perform event handling. Here, we are writing the code to start and stop service. Additionally, calling the second activity on buttonNext.
File: MainActivity.java 1. package com.example.serviceexampleaudio; 2. import android.app.Activity; 3. import android.content.Intent; 4. import android.os.Bundle; 5. import android.view.View; 6. import android.view.View.OnClickListener; 7. import android.widget.Button; 8. public class MainActivity extends Activity implements OnClickListener { 9.
Button buttonStart, buttonStop,buttonNext;
10.
@Override
11.
public void onCreate(Bundle savedInstanceState) {
12.
super.onCreate(savedInstanceState);
13.
setContentView(R.layout.activity_main);
14. 15.
buttonStart = (Button) findViewById(R.id.buttonStart);
16.
buttonStop = (Button) findViewById(R.id.buttonStop);
17.
buttonNext = (Button) findViewById(R.id.buttonNext);
18. 19.
buttonStart.setOnClickListener(this);
20.
buttonStop.setOnClickListener(this);
21.
buttonNext.setOnClickListener(this);
22.
}
23.
public void onClick(View src) {
24.
switch (src.getId()) {
25.
case R.id.buttonStart:
26.
startService(new Intent(this, MyService.class));
27.
break;
28.
case R.id.buttonStop:
29.
stopService(new Intent(this, MyService.class));
30.
break;
31.
case R.id.buttonNext:
32.
Intent intent=new Intent(this,NextPage.class);
33.
startActivity(intent);
34.
break;
35.
}
36.
}
37. }
NextPage class Now, create another activity.
File: NextPage.java 1. package com.example.serviceexampleaudio; 2. import android.app.Activity; 3. import android.os.Bundle; 4. 5. public class NextPage extends Activity { 6.
@Override
7.
public void onCreate(Bundle savedInstanceState) {
8.
super.onCreate(savedInstanceState);
9.
setContentView(R.layout.activity_next);
10. } 11. }
Declare the Service in the AndroidManifest.xml file Finally, declare the service in the manifest file.
File: AndroidManifest.xml Let's see the complete AndroidManifest.xml file 1. 2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
3.
package="com.example.serviceexampleaudio"
4.
android:versionCode="1"
5.
android:versionName="1.0" >
6. 7.
<uses-sdk
8.
android:minSdkVersion="8"
9.
android:targetSdkVersion="17" />
10. 11.
12.
android:allowBackup="true"
13.
android:icon="@drawable/ic_launcher"
14.
android:label="@string/app_name"
15.
android:theme="@style/AppTheme" rel="nofollow">
16.
17.
android:name="com.example.serviceexampleaudio.MainActivity"
18.
android:label="@string/app_name" rel="nofollow">
19.
20.
21. 22. 23. 24.
25. 26.
<service
27.
android:name=".MyService"
28.
android:enabled="true" />
29. 30. 31.
32. 33.
Android Animation Example Android provides a large number of classes and interface for the animation development. Most of the classes and interfaces are given in android.animation package. Android Animation enables you to change the object property and behavior at run time. There are various ways to do animation in android. The AnimationDrawable class provides methods to start and end the animation. Even, you can use time based animation. Let's have a look at the simple example of android animation. activity_main.xml
You need to have a view only. File: activity_main.xml 1. 10. 11. 13. 14. File: logo.xml
Have a image view only. 1. 2. 7. 8.
MainActivity class File: MainActivity.java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34.
package com.javatpoint.animation; import android.os.Bundle; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.widget.ImageView; public class MainActivity extends Activity { ImageView anm; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.logo); anm = (ImageView)findViewById(R.id.anm); anm.setBackgroundResource(R.drawable.animation); // the frame-by-frame animation defined as a xml file within the drawable folder /* * NOTE: It's not possible to start the animation during the onCreate. */ } public void onWindowFocusChanged (boolean hasFocus) { super.onWindowFocusChanged(hasFocus); AnimationDrawable frameAnimation = (AnimationDrawable) anm.getBackground(); if(hasFocus) { frameAnimation.start(); } else { frameAnimation.stop(); } } }
You need to create animation.xml file inside res/drawable-hdpi directory. You need to have many images. Here, we are using 14 images and all the 14 images are located inside res/drawable-mdpi directory. File: animation.xml
1. 2. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36.