0% found this document useful (0 votes)
133 views

Android Custom Toast Example

The document discusses creating a custom toast notification in Android. It describes how to create a custom XML layout file for the toast containing an ImageView and TextView. It then shows code for inflating this custom layout and displaying it as a toast notification to allow customizing the toast appearance.

Uploaded by

Sourav Das
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views

Android Custom Toast Example

The document discusses creating a custom toast notification in Android. It describes how to create a custom XML layout file for the toast containing an ImageView and TextView. It then shows code for inflating this custom layout and displaying it as a toast notification to allow customizing the toast appearance.

Uploaded by

Sourav Das
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Android Custom Toast Example

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

activity_main.xml

Drag the component that you want to display on the main activity.

File: activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />

</RelativeLayout>

customtoast.xml

Create another xml file inside the layout directory. Here we are having ImageView and TextView in this
xml file.

File: customtoast.xml

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


<LinearLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#F14E23"
>

<ImageView
android:id="@+id/custom_toast_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/hello_world"
android:src="@drawable/ic_launcher"/>

<TextView
android:id="@+id/custom_toast_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/Toast"
android:text="@string/Toast" />
</LinearLayout>

Activity class

Now write the code to display the custom toast.

File: MainActivity.java

package com.example.customtoast2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class MainActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Creating the LayoutInflater instance


LayoutInflater li = getLayoutInflater();
//Getting the View object as defined in the customtoast.xml file
View layout = li.inflate(R.layout.customtoast,
(ViewGroup) findViewById(R.id.custom_toast_layout));

//Creating the Toast object


Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layout);//setting the view of custom toast layout
toast.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

Output:

Android AlertDialog Example

Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can be
used to interrupt and ask the user about his/her choice to continue or discontinue.

Android AlertDialog is composed of three regions: title, content area and action buttons.

Android AlertDialog is the subclass of Dialog class.


Android AlertDialog Example

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

activity_main.xml

You can have multiple components, here we are having only a textview.

File: activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />

</RelativeLayout>

strings.xml

Optionally, you can store the dialog message and title in the strings.xml file.

File: strings.xml

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


<resources>

<string name="app_name">alertdialog</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="dialog_message">Welcome to Alert Dialog</string>

<string name="dialog_title">Javatpoint Alert Dialog</string>


</resources>

Activity class

Let's write the code to create and show the AlertDialog.


File: MainActivity.java

package com.example.alertdialog;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

AlertDialog.Builder builder = new AlertDialog.Builder(this);


//Uncomment the below code to Set the message and title from the strings.xml file
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);

//Setting message manually and performing action on button click


builder.setMessage("Do you want to close this application ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});

//Creating dialog box


AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("AlertDialogExample");
alert.show();
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

Output:

Android Spinner Example


Android Spinner is like the combox box of AWT or Swing. It can be used to display the multiple
options to the user in which only one item can be selected by the user.

Android spinner is like the drop down menu with multiple values from which the end user can select only
one value.

Android spinner is associated with AdapterView. So you need to use one of the adapter classes with
spinner.

Android Spinner class is the subclass of AsbSpinner class.

Android Spinner Example

In this example, we are going to display the country list. You need to use ArrayAdapter class to store the
country list.

Let's see the simple example of spinner in android.

activity_main.xml

Drag the Spinner from the pallete, now the activity_main.xml file will like this:

File: activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp" />

</RelativeLayout>

Activity class

Let's write the code to display item on the spinner and perform event handling.

File: MainActivity.java

package com.example.spinner;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements


AdapterView.OnItemSelectedListener {

String[] country = { "India", "USA", "China", "Japan", "Other", };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.spinner1);
spin.setOnItemSelectedListener(this);

//Creating the ArrayAdapter instance having the country list


ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,country);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(),country[position] ,Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Output:

Android AutoCompleteTextView Example

Android AutoCompleteTextView completes the word based on the reserved words, so no need to write
all the characters of the word.

Android AutoCompleteTextView is a editable text field, it displays a list of suggestions in a drop down
menu from which user can select only one suggestion or value.

Android AutoCompleteTextView is the subclass of EditText class. The MultiAutoCompleteTextView is


the subclass of AutoCompleteTextView class.
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

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="@string/what_is_your_favourite_programming_language_" />

<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginLeft="36dp"
android:layout_marginTop="17dp"
android:ems="10"
android:text="">

<requestFocus />
</AutoCompleteTextView>

</RelativeLayout>
Activity class

Let's write the code of AutoCompleteTextView.

File: MainActivity.java

package com.example.autocompletetextview;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class MainActivity extends Activity {


String[] language ={"C","C++","Java",".NET","iPhone","Android","ASP.NET","PHP"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//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.autoCompleteTextView1
);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
actv.setTextColor(Color.RED);

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}
Android RatingBar Example

Android RatingBar can be used to get the rating from the user. The Rating returns a floating-point
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

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<RatingBar
android:id="@+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/ratingBar1"
android:layout_below="@+id/ratingBar1"
android:layout_marginLeft="92dp"
android:layout_marginTop="66dp"
android:text="submit" />

</RelativeLayout>

Activity class

Let's write the code to display the rating of the user.

File: MainActivity.java

package com.example.rating;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Toast;

public class MainActivity extends Activity {


RatingBar ratingbar1;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}

public void addListenerOnButtonClick(){


ratingbar1=(RatingBar)findViewById(R.id.ratingBar1);
button=(Button)findViewById(R.id.button1);
//Performing action on Button Click
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
//Getting the rating and displaying it on the toast
String rating=String.valueOf(ratingbar1.getRating());
Toast.makeText(getApplicationContext(), rating, Toast.LENGTH_LONG).show();
}

});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

Output:

Android WebView Example


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 = "<html><body><h1>Hello, Javatpoint!</h1></body></html>";


2. mywebview.loadData(data, "text/html", "UTF-8");

Android WebView Example


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 = "<html><body><h1>Hello, Javatpoint!</h1></body></html>";


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. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".MainActivity" >
6.
7. <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. </RelativeLayout>

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 = "<html><body><h1>Hello, Javatpoint!</h1></body></html>";
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. }
Let's see the output if you load the HTML page.
Android SeekBar Example

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp" />

</RelativeLayout>

Activity class

Let's see the Activity class displaying seek bar and performing event handling.

File: MainActivity.java

package com.example.seekbar;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity implements OnSeekBarChangeListener{
SeekBar seekBar1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

seekBar1=(SeekBar)findViewById(R.id.seekBar1);
seekBar1.setOnSeekBarChangeListener(this);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
Toast.makeText(getApplicationContext(),"seekbar progress: "+progress, Toast.LENGTH_SHORT).sho
w();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch started!", Toast.LENGTH_SHORT).show();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch stopped!", Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
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

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="50dp"
android:layout_marginTop="36dp"
android:text="Current Date:" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="140dp"
android:text="Change Date" />

<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="30dp" />

</RelativeLayout>
Activity class

File: MainActivity.java

package com.example.datepicker2;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


DatePicker picker;
Button displayDate;
TextView textview1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textview1=(TextView)findViewById(R.id.textView1);
picker=(DatePicker)findViewById(R.id.datePicker1);
displayDate=(Button)findViewById(R.id.button1);

textview1.setText(getCurrentDate());

displayDate.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
textview1.setText(getCurrentDate());
}

});
}
public String getCurrentDate(){
StringBuilder builder=new StringBuilder();
builder.append("Current Date: ");
builder.append((picker.getMonth() + 1)+"/");//month is 0 based
builder.append(picker.getDayOfMonth()+"/");
builder.append(picker.getYear());
return builder.toString();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

Android TimePicker Example

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

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="86dp" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/timePicker1"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp"
android:text="Current Time:" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/timePicker1"
android:layout_below="@+id/timePicker1"
android:layout_marginLeft="37dp"
android:layout_marginTop="55dp"
android:text="Change Time" />

</RelativeLayout>

Activity class
File: MainActivity.java

package com.example.timepicker1;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class MainActivity extends Activity {


TextView textview1;
TimePicker timepicker1;
Button changetime;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textview1=(TextView)findViewById(R.id.textView1);
timepicker1=(TimePicker)findViewById(R.id.timePicker1);
//Uncomment the below line of code for 24 hour view
timepicker1.setIs24HourView(true);
changetime=(Button)findViewById(R.id.button1);

textview1.setText(getCurrentTime());

changetime.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
textview1.setText(getCurrentTime());
}
});

public String getCurrentTime(){


String currentTime="Current Time: "+timepicker1.getCurrentHour()+":"+timepicker1.getCurrentMinute
();
return currentTime;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}
Android Analog clock and Digital clock example

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

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

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<AnalogClock
android:id="@+id/analogClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp" />

<DigitalClock
android:id="@+id/digitalClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/analogClock1"
android:layout_centerHorizontal="true"
android:layout_marginTop="81dp"
android:text="DigitalClock" />

</RelativeLayout>
Activity class

We have not write any code here.

File: MainActivity.java

package com.example.analogdigital;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Output:

Android ProgressBar Example

We can display the 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

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="116dp"
android:text="download file" />

</RelativeLayout>

Activity class

Let's write the code to display the progress bar dialog box.

File: MainActivity.java

package com.example.progressbar1;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
Button btnStartProgress;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private long fileSize = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick() {
btnStartProgress = (Button) findViewById(R.id.button1);
btnStartProgress.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// creating progress bar dialog
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//reset progress bar and filesize status
progressBarStatus = 0;
fileSize = 0;

new Thread(new Runnable() {


public void run() {
while (progressBarStatus < 100) {
// performing operation
progressBarStatus = doOperation();
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
// Updating the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// performing operation if file is downloaded,
if (progressBarStatus >= 100) {
// sleeping for 1 second after operation completed
try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}//end of onClick method
});
}
// checking how much file is downloaded and updating the filesize
public int doOperation() {
//The range of ProgressDialog starts from 0 to 10000
while (fileSize <= 10000) {
fileSize++;
if (fileSize == 1000) {
return 10;
} else if (fileSize == 2000) {
return 20;
} else if (fileSize == 3000) {
return 30;
} else if (fileSize == 4000) {
return 40;//you can add more else if
} else{
return 100;
}
}//end of while
return 100;
}//end of doOperation

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Output:

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

package com.example.activitylifecycle;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}

Output:

You will not see any output on the emulator or device. You need to open logcat.

Now see on the logcat: onCreate, onStart and onResume methods are invoked.
Now click on the HOME Button. You will see onPause method is invoked.
After a while, you will see onStop method is invoked.

Now see on the emulator. It is on the home. Now click on the center button to launch the app again.

Now click on the lifecycleactivity icon.


Now see on the logcat: onRestart, onStart and onResume methods are invoked.

If you see the emulator, application is started again.


Now click on the back button. Now you will see onPause methods is invoked.

After a while, you will see onStop and onDestroy methods are invoked.

You might also like