Android Widgets
There are given a lot of android widgets with simplified examples such as Button,
EditText, AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar
etc.
Android widgets are easy to learn. The widely used android widgets with examples are
given below:
Android Button
Let's learn how to perform event handling on button click.
Android Widgets
There are given a lot of android widgets with simplified examples such as Button,
EditText, AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar
etc.
Android widgets are easy to learn. The widely used android widgets with examples
are given below:
Android Button
Let's learn how to perform event handling on button click.
Android Toast
Displays information for the short duration of time.
Custom Toast
We are able to customize the toast, such as we can display image on the toast
ToggleButton
It has two states ON/OFF.
CheckBox
Let's see the application of simple food ordering.
AlertDialog
AlertDialog displays a alert dialog containing the message with OK and Cancel
buttons.
Spinner
Spinner displays the multiple options, but only one can be selected at a time.
AutoCompleteTextView
Let's see the simple example of AutoCompleteTextView.
RatingBar
RatingBar displays the rating bar.
DatePicker
Datepicker displays the datepicker dialog that can be used to pick the date.
TimePicker
TimePicker displays the timepicker dialog that can be used to pick the time.
ProgressBar
ProgressBar displays progress task.
Android Button Example
Android Button represents a push-button. The [Link] 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.
Android Button Example with Listener
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.
We can perform action on button using different types such as calling listener on button
or adding onClick property of button in activity's xml file.
Android Toast Example
Andorid Toast can be used to display information for the short period of time. A toast
contains message to be displayed quickly and disappears after sometime.
The [Link] class is the subclass of [Link] class.
You can also create custom toast as well for example toast displaying image. You can
visit next page to see the code for custom toast.
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 Description
public static Toast makeText(Context context, makes the toast containing text and
CharSequence text, int duration) duration.
public void show() displays toast.
public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.
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.
1. <ImageView
2. android:id="@+id/custom_toast_image"
3. android:layout_width="wrap_content"
4. android:layout_height="wrap_content"
5. android:contentDescription="Hello world"
6. android:src="@drawable/jtp_logo"/>
Android ToggleButton Example
Android Toggle Button can be used to display checked/unchecked (On/Off) state on
the button.
It is beneficial if user have to change the setting between two states. It can be used to
On/Off Sound, Wifi, Bluetooth etc.
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.
1. android:textOff="Off"
2. android:textOn="On"
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 Changes the checked state of this button.
checked)
Android CheckBox Example
Android CheckBox is a type of two state button either checked or unchecked.
There can be a lot of usage of checkboxes. For example, it can be used to know the
hobby of the user, activate/deactivate the specific action etc.
Android CheckBox class is the subclass of CompoundButton class.
Android CheckBox class
The [Link] 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 false.
public void setChecked(boolean status) Changes the state of the CheckBox.
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.
Method Description
public [Link] This method is used to set the title of
setTitle(CharSequence) AlertDialog.
public [Link] This method is used to set the message
setMessage(CharSequence) for AlertDialog.
public [Link] setIcon(int) This method is used to set the icon over
AlertDialog.
1.
import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8.
9. public class MainActivity extends AppCompatActivity {
10. Button closeButton;
11. [Link] builder;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. [Link](savedInstanceState);
15. setContentView([Link].activity_main);
16.
17. closeButton = (Button) findViewById([Link]);
18. builder = new [Link](this);
19. [Link](new [Link]() {
20. @Override
21. public void onClick(View v) {
22.
23. //Uncomment the below code to Set the message and title from the strings.x
ml file
24. [Link]([Link].dialog_message) .setTitle([Link].dialog_title);
25.
26. //Setting message manually and performing action on button click
27. [Link]("Do you want to close this application ?")
28. .setCancelable(false)
29. .setPositiveButton("Yes", new [Link]() {
30. public void onClick(DialogInterface dialog, int id) {
31. finish();
32. [Link](getApplicationContext(),"you choose yes action fo
r alertbox",
33. Toast.LENGTH_SHORT).show();
34. }
35. })
36. .setNegativeButton("No", new [Link]() {
37. public void onClick(DialogInterface dialog, int id) {
38. // Action for 'NO' Button
39. [Link]();
40. [Link](getApplicationContext(),"you choose no action for
alertbox",
41. Toast.LENGTH_SHORT).show();
42. }
43. });
44. //Creating dialog box
45. AlertDialog alert = [Link]();
46. //Setting the title manually
47. [Link]("AlertDialogExample");
48. [Link]();
49. }
50. });
51. }
52. }
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 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.
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.
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. public class MainActivity extends AppCompatActivity {
8. String[] language ={"C","C++","Java",".NET","iPhone","Android","[Link]","PHP"};
9. @Override
10. protected void onCreate(Bundle savedInstanceState) {
11. [Link](savedInstanceState);
12. setContentView([Link].activity_main);
13. //Creating the instance of ArrayAdapter containing list of language names
14. ArrayAdapter<String> adapter = new ArrayAdapter<String>
15. (this,[Link].select_dialog_item,language);
16. //Getting the instance of AutoCompleteTextView
17. AutoCompleteTextView actv = (AutoCompleteTextView)findViewById([Link]
mpleteTextView);
18. [Link](1);//will start working from first character
19. [Link](adapter);//setting the adapter data into the AutoCompleteTextVie
w
20. [Link]([Link]);
21. }
22. }
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 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 [Link] is the subclass of FrameLayout class.
Android DatePicker Example
Let's see the simple example of datepicker widget in android.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class MainActivity extends AppCompatActivity {
11. DatePicker picker;
12. Button displayDate;
13. TextView textview1;
14. @Override
15. protected void onCreate(Bundle savedInstanceState) {
16. [Link](savedInstanceState);
17. setContentView([Link].activity_main);
18.
19. textview1=(TextView)findViewById([Link].textView1);
20. picker=(DatePicker)findViewById([Link]);
21. displayDate=(Button)findViewById([Link].button1);
22.
23. [Link]("Current Date: "+getCurrentDate());
24.
25. [Link](new [Link](){
26. @Override
27. public void onClick(View view) {
28.
29. [Link]("Change Date: "+getCurrentDate());
30. }
31.
32. });
33.
34. }
35. public String getCurrentDate(){
36. StringBuilder builder=new StringBuilder();;
37. [Link](([Link]() + 1)+"/");//month is 0 based
38. [Link]([Link]()+"/");
39. [Link]([Link]());
40. return [Link]();
41. }
42. }
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 [Link] is the subclass of FrameLayout class.
Android TimePicker Example
Let's see a simple example of android time picker.
1. package [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8.
9. public class MainActivity extends AppCompatActivity {
10. TextView textview1;
11. TimePicker timepicker;
12. Button changetime;
13. @Override
14. protected void onCreate(Bundle savedInstanceState) {
15. [Link](savedInstanceState);
16. setContentView([Link].activity_main);
17.
18. textview1=(TextView)findViewById([Link].textView1);
19. timepicker=(TimePicker)findViewById([Link]);
20. //Uncomment the below line of code for 24 hour view
21. timepicker.setIs24HourView(true);
22. changetime=(Button)findViewById([Link].button1);
23.
24. [Link](getCurrentTime());
25.
26. [Link](new [Link](){
27. @Override
28. public void onClick(View view) {
29. [Link](getCurrentTime());
30. }
31. });
32.
33. }
34.
35. public String getCurrentTime(){
36. String currentTime="Current Time: "+[Link]()+":"+timepicker
.getCurrentMinute();
37. return currentTime;
38. }
39.
40. }
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 [Link] 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.
1. package [Link];
2.
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class MainActivity extends AppCompatActivity {
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. [Link](savedInstanceState);
19. setContentView([Link].activity_main);
20. addListenerOnButtonClick();
21. }
22. public void addListenerOnButtonClick() {
23. btnStartProgress = findViewById([Link]);
24. [Link](new [Link](){
25.
26. @Override
27. public void onClick(View v) {
28. // creating progress bar dialog
29. progressBar = new ProgressDialog([Link]());
30. [Link](true);
31. [Link]("File downloading ...");
32. [Link](ProgressDialog.STYLE_HORIZONTAL);
33. [Link](0);
34. [Link](100);
35. [Link]();
36. //reset progress bar and filesize status
37. progressBarStatus = 0;
38. fileSize = 0;
39.
40. new Thread(new Runnable() {
41. public void run() {
42. while (progressBarStatus < 100) {
43. // performing operation
44. progressBarStatus = doOperation();
45. try {
46. [Link](1000);
47. } catch (InterruptedException e) {
48. [Link]();
49. }
50. // Updating the progress bar
51. [Link](new Runnable() {
52. public void run() {
53. [Link](progressBarStatus);
54. }
55. });
56. }
57. // performing operation if file is downloaded,
58. if (progressBarStatus >= 100) {
59. // sleeping for 1 second after operation completed
60. try {
61. [Link](1000);
62. } catch (InterruptedException e) {
63. [Link]();
64. }
65. // close the progress bar dialog
66. [Link]();
67. }
68. }
69. }).start();
70. }//end of onClick method
71. });
72. }
73. // checking how much file is downloaded and updating the filesize
74. public int doOperation() {
75. //The range of ProgressDialog starts from 0 to 10000
76. while (fileSize <= 10000) {
77. fileSize++;
78. if (fileSize == 1000) {
79. return 10;
80. } else if (fileSize == 2000) {
81. return 20;
82. } else if (fileSize == 3000) {
83. return 30;
84. } else if (fileSize == 4000) {
85. return 40; // you can add more else if
86. }
87. /* else {
88. return 100;
89. }*/
90. }//end of while
91. return 100;
92. }//end of doOperation
93. }