Monday 4 February 2013

Time Picker in Android

Here we see that how we use Time Picker Dialog to pick time and show in textview :-

2) XML Layout for TimePicker


                     <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" >

                            <EditText
                                android:id="@+id/editText3"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:ems="10"
                                android:hint="Select Time" />

                            <Button
                                android:id="@+id/button3"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:text="Pick" />
                        </LinearLayout>


2) Java Code For Time Picker
      public class Scheduler extends Activity implements OnClickListener {
private int hour;
private int minute;
static final int Time_DIALOG_ID = 125;
private Button b3;
private EditText time;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
b3=(Button)findViewById(R.id.button3);
b3.setOnClickListener(this);
contact=(EditText)findViewById(R.id.editText1);
date=(EditText)findViewById(R.id.editText2);
time=(EditText)findViewById(R.id.editText3);
final Calendar c = Calendar.getInstance();
        hour=c.get(Calendar.HOUR);
                minute=c.get(Calendar.MINUTE);
}
@Override
public void onClick(View arg0) {
if(arg0==b3)
{
showDialog(Time_DIALOG_ID);
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case Time_DIALOG_ID:
return new TimePickerDialog(this, timepickerlistner,hour, minute,true);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timepickerlistner =new OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
hour = arg1;
minute = arg2;
time.setText(new StringBuilder().append(hour)
.append(":").append(minute).append(" "));
}
};
}



No comments:

Post a Comment