Android Custom Toast Example
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
<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
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;
Output:
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.
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
<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>
Activity class
package com.example.alertdialog;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@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 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.
In this example, we are going to display the country list. You need to use ArrayAdapter class to store the
country list.
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;
@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);
@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 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.
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.
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
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;
@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.
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
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;
});
}
@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:
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.
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.
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.
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.
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.
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;
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 widget is used to select date. It allows you to select time by hour and minute. You
cannot select time by seconds.
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;
@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());
}
});
}
Android Analog clock and Digital clock example
Android analog and digital clocks are used to show time in android application.
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
File: MainActivity.java
package com.example.analogdigital;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
@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:
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 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;
@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:
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
Method Description
onResume called when activity will start interacting with the user.
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.
After a while, you will see onStop and onDestroy methods are invoked.