Android Widgets
Android Widgets
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
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
Android Toast
Custom Toast
We are able to customize the toast, such as we can display image on the toast
ToggleButton
CheckBox
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
RatingBar
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.
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.
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.
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.
Method Description
public static Toast makeText(Context context, makes the toast containing text and
CharSequence text, int duration) duration.
public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.
It is beneficial if user have to change the setting between two states. It can be used to
On/Off Sound, Wifi, Bluetooth etc.
1. android:textOff="Off"
2. android:textOn="On"
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.
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.
There are many inherited methods of View, TextView, and Button classes in the
CheckBox class. Some of them are as follows:
Method Description
Android AlertDialog is composed of three regions: title, content area and action buttons.
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 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.
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 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.
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. }
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:
In this example, we are displaying the progress dialog for dummy file download
operation.
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. }