Android Widgets

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

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

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 android.widget.Toast class is the subclass of java.lang.Object 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 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 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 AlertDialog.Builder This method is used to set the title of


setTitle(CharSequence) AlertDialog.

public AlertDialog.Builder This method is used to set the message


setMessage(CharSequence) for AlertDialog.

public AlertDialog.Builder setIcon(int) This method is used to set the icon over
AlertDialog.

1.
import android.content.DialogInterface;
2. import android.support.v7.app.AppCompatActivity;
3. import android.os.Bundle;
4. import android.view.View;
5. import android.widget.Button;
6. import android.app.AlertDialog;
7. import android.widget.Toast;
8.
9. public class MainActivity extends AppCompatActivity {
10. Button closeButton;
11. AlertDialog.Builder builder;
12. @Override
13. protected void onCreate(Bundle savedInstanceState) {
14. super.onCreate(savedInstanceState);
15. setContentView(R.layout.activity_main);
16.
17. closeButton = (Button) findViewById(R.id.button);
18. builder = new AlertDialog.Builder(this);
19. closeButton.setOnClickListener(new View.OnClickListener() {
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. builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
25.
26. //Setting message manually and performing action on button click
27. builder.setMessage("Do you want to close this application ?")
28. .setCancelable(false)
29. .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
30. public void onClick(DialogInterface dialog, int id) {
31. finish();
32. Toast.makeText(getApplicationContext(),"you choose yes action fo
r alertbox",
33. Toast.LENGTH_SHORT).show();
34. }
35. })
36. .setNegativeButton("No", new DialogInterface.OnClickListener() {
37. public void onClick(DialogInterface dialog, int id) {
38. // Action for 'NO' Button
39. dialog.cancel();
40. Toast.makeText(getApplicationContext(),"you choose no action for
alertbox",
41. Toast.LENGTH_SHORT).show();
42. }
43. });
44. //Creating dialog box
45. AlertDialog alert = builder.create();
46. //Setting the title manually
47. alert.setTitle("AlertDialogExample");
48. alert.show();
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 android.graphics.Color;
2. import android.support.v7.app.AppCompatActivity;
3. import android.os.Bundle;
4. import android.widget.ArrayAdapter;
5. import android.widget.AutoCompleteTextView;
6.
7. public class MainActivity extends AppCompatActivity {
8. String[] language ={"C","C++","Java",".NET","iPhone","Android","ASP.NET","PHP"};
9. @Override
10. protected void onCreate(Bundle savedInstanceState) {
11. super.onCreate(savedInstanceState);
12. setContentView(R.layout.activity_main);
13. //Creating the instance of ArrayAdapter containing list of language names
14. ArrayAdapter<String> adapter = new ArrayAdapter<String>
15. (this,android.R.layout.select_dialog_item,language);
16. //Getting the instance of AutoCompleteTextView
17. AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.id.autoCo
mpleteTextView);
18. actv.setThreshold(1);//will start working from first character
19. actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextVie
w
20. actv.setTextColor(Color.RED);
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 android.widget.DatePicker is the subclass of FrameLayout class.

Android DatePicker Example


Let's see the simple example of datepicker widget in android.

1. package example.javatpoint.com.datepicker;
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.DatePicker;
8. import android.widget.TextView;
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. super.onCreate(savedInstanceState);
17. setContentView(R.layout.activity_main);
18.
19. textview1=(TextView)findViewById(R.id.textView1);
20. picker=(DatePicker)findViewById(R.id.datePicker);
21. displayDate=(Button)findViewById(R.id.button1);
22.
23. textview1.setText("Current Date: "+getCurrentDate());
24.
25. displayDate.setOnClickListener(new View.OnClickListener(){
26. @Override
27. public void onClick(View view) {
28.
29. textview1.setText("Change Date: "+getCurrentDate());
30. }
31.
32. });
33.
34. }
35. public String getCurrentDate(){
36. StringBuilder builder=new StringBuilder();;
37. builder.append((picker.getMonth() + 1)+"/");//month is 0 based
38. builder.append(picker.getDayOfMonth()+"/");
39. builder.append(picker.getYear());
40. return builder.toString();
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 android.widget.TimePicker is the subclass of FrameLayout class.

Android TimePicker Example


Let's see a simple example of android time picker.

1. package example.javatpoint.com.timepicker;
2. import android.support.v7.app.AppCompatActivity;
3. import android.os.Bundle;
4. import android.view.View;
5. import android.widget.Button;
6. import android.widget.TextView;
7. import android.widget.TimePicker;
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. super.onCreate(savedInstanceState);
16. setContentView(R.layout.activity_main);
17.
18. textview1=(TextView)findViewById(R.id.textView1);
19. timepicker=(TimePicker)findViewById(R.id.timePicker);
20. //Uncomment the below line of code for 24 hour view
21. timepicker.setIs24HourView(true);
22. changetime=(Button)findViewById(R.id.button1);
23.
24. textview1.setText(getCurrentTime());
25.
26. changetime.setOnClickListener(new View.OnClickListener(){
27. @Override
28. public void onClick(View view) {
29. textview1.setText(getCurrentTime());
30. }
31. });
32.
33. }
34.
35. public String getCurrentTime(){
36. String currentTime="Current Time: "+timepicker.getCurrentHour()+":"+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 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.
1. package example.javatpoint.com.progressbar;
2.
3. import android.app.ProgressDialog;
4. import android.os.Handler;
5. import android.support.v7.app.AppCompatActivity;
6. import android.os.Bundle;
7. import android.view.View;
8. import android.widget.Button;
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. super.onCreate(savedInstanceState);
19. setContentView(R.layout.activity_main);
20. addListenerOnButtonClick();
21. }
22. public void addListenerOnButtonClick() {
23. btnStartProgress = findViewById(R.id.button);
24. btnStartProgress.setOnClickListener(new View.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. new Thread(new Runnable() {
41. public void run() {
42. while (progressBarStatus < 100) {
43. // performing operation
44. progressBarStatus = doOperation();
45. try {
46. Thread.sleep(1000);
47. } catch (InterruptedException e) {
48. e.printStackTrace();
49. }
50. // Updating the progress bar
51. progressBarHandler.post(new Runnable() {
52. public void run() {
53. progressBar.setProgress(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. Thread.sleep(1000);
62. } catch (InterruptedException e) {
63. e.printStackTrace();
64. }
65. // close the progress bar dialog
66. progressBar.dismiss();
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. }

You might also like