Thursday, August 27, 2015

Android TimePicker Example

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#d8dcda"
    >
    <TimePicker
        android:id="@+id/tp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:timePickerMode="spinner"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select time."
        android:fontFamily="sans-serif-condensed"
        android:textSize="20dp"
        android:textColor="#c62f93"
        android:padding="15dp"
        android:layout_toRightOf="@id/tp"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        TimePicker tp = (TimePicker) findViewById(R.id.tp);
        final TextView tv = (TextView) findViewById(R.id.tv);

        // Time change listener for time picker
        tp.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                // Display the updated time on TextView
                tv.setText("Your selected time is : \n");
                tv.setText(tv.getText() + "HH : MM\n" + hourOfDay + " : " + minute);
            }
        });
   }
}


More android examples