How to use time change selection listener on TimePicker widget to show selected time.
In this tutorial we are setting up setOnTimeChangedListener() method on time picker tool widget to directly get time from user into android application. So here is the complete step by step tutorial for Add setOnTimeChangedListener on TimePicker in android.
How to Add setOnTimeChangedListener on TimePicker in android.
Code for MainActivity.java file.
package com.setontimechangedlistener_timepicker_android_examples.com; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.widget.TimePicker; public class MainActivity extends Activity { TimePicker timepicker; TextView timedisplay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); timedisplay = (TextView)findViewById(R.id.textView1); timepicker = (TimePicker)findViewById(R.id.timePicker1); timepicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub timedisplay.setText(hourOfDay + ":" + minute); } }); } }
Code for activity_main.xml layout file.
<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="com.setontimechangedlistener_timepicker_android_examples.com.MainActivity" > <TimePicker android:id="@+id/timePicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/timePicker1" android:layout_centerHorizontal="true" android:layout_marginBottom="28dp" android:text="Time Display Here" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>
Screenshot: