Android Custom Toggle Button Example (iOS like toggle buttons)

Toggle buttons are a great way of getting user input when we need only either yes or no from user. Technically speaking, when we need user input in boolean form- toggle buttons can come handy.

Adding a toggle button to your view and getting its status is very easy, you can have a look what Google has to say about them here.

But, toggle buttons provided with sdk are slightly dull and you just can’t go around and use them everywhere. Well, you can use different images for toggle button states. You can define a button for its checked state and other button for unchecked state. With this you can get a switch-look also.

Lets look how you can get a custom toggle button in your application. The images we are using for different states are inspired from toggle button of iOS, I found them classy (lets have a bit open mind here 😉 ).

In action:

Custom toggle button android

Full source code at github.

 Put toggle_off.png and toggle_on.png in drawable folder. You can replace them with your own images.

toggle_on
toggle_off

Create toggle_selector.xml in drawable. Define drawables for different states.

toggle_selector.xml

<?xml version="1.0"encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item
android:drawable="@drawable/toggle_on"
android:state_checked="true"/>

   <item
android:drawable="@drawable/toggle_off"
android:state_checked="false"/>
</selector>

Define ToggleButton in activity_main.xml


<ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/toggle_selector"
        android:checked="false"
        android:text=""
        android:textOff=""
        android:textOn="" />

Important: We have to set background of our toggle button to toggle_selector defined in drawable folder. It will set the image according to its state. Also, to get desired effect as shown in demo above – we must set android:textOff and android:textOn to empty string otherwise text will appear on top of our images.

To get the status from ToggleButton, we can set a onCheckedChangeListener on our ToggleButton as shown below.

toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
				text.setText("Status: " + isChecked);
			}
		});

We are updating text of TextView when toggleButton is tapped. Checkout full source code on github.

Android Date Picker and Time Picker Example

Many times arises a need to take date and time input from user. Then starts a series of converting tedious date formats and shameless workarounds. This is a tutorial explaining how to use Date Picker and Time Picker in Android. It presents an aesthetic interface to user and provides data in standard format to programmer. Plus, its a good UI practice.

To present these dialogs, we will use DialogFragment to host them.

If you are a code-first tutorial-later person then you can have a look at sample project hosted on github.

Time Picker

To integrate Time Picker Dialog in your Activity you need to define an inner class like below.


public class TimePickerFragment extends DialogFragment implements
			TimePickerDialog.OnTimeSetListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current time as the default values for the picker
			final Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);

			// Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(context, this, hour, minute,
					DateFormat.is24HourFormat(context));
		}

		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// Do something with the time chosen by the user
			
		}
	}



onCreateDialog returns our TimePicker dialog, we are initializing it with device’s current time. onTimeSet is called when a time is selected in dialog. We can do whatever we want to do with that time.

We can show this TimePicker Dialog on any event such as button click using following code.

DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");

Look closely in onTimeSet we have hourOfDay, that will be in 24 hour format. To convert it into 12 hour format and display AM/PM we need to tweak it a bit as show below.

	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String AM_PM = "";

			Calendar datetime = Calendar.getInstance();
			datetime.set(Calendar.HOUR_OF_DAY, hourOfDay);
			datetime.set(Calendar.MINUTE, minute);

			if (datetime.get(Calendar.AM_PM) == Calendar.AM)
				AM_PM = "AM";
			else if (datetime.get(Calendar.AM_PM) == Calendar.PM)
				AM_PM = "PM";

			String hours = (datetime.get(Calendar.HOUR) == 0) ? "12" : datetime
					.get(Calendar.HOUR) + "";
			
			Log.d(“Time: ”, hours + “ : ” + minute + “  ” + AM_PM );

}

Check out sample project hosted on github for full source code.

Date Picker

For using DatePicker, TimePicker like approach is used.

A class needs to be defined like below.

public class DatePickerFragment extends DialogFragment implements
			DatePickerDialog.OnDateSetListener {

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		public void onDateSet(DatePicker view, int year, int month, int day) {
			// Do something with the date chosen by the user

			/*
			 * MOnth returned from datepicker is always one less than actual
			 * value for example: December will be 11, January will be 0 and so
			 * on.
			 */

			month = month + 1;

			Log.d(“Date: ” , day + " - " + month + " - " + year); 

		}
	}


We can call it with following code.



DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");


In onCreateDialog we intialize our dialog with device’s current date. onDateSet is called when a date is selected in dialog.

Note that in onDateSet, month returned is one less than the actual month so we need to increment it by 1.

Check out full source code of sample project at github.

See it in action:

Date and Time Picker Android