Monday 4 February 2013

Date Picker in Android

In This Section we Know the how to use Date Picker Dialog in android to pick date and show in textview:

1) Layout for  Date Picker Activity

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

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

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

2) Java Activity Code :
        public class Scheduler extends Activity implements OnClickListener {
private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 123;
private Button b1;
private EditText date;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(this);
date=(EditText)findViewById(R.id.editText2);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
        }
@Override
public void onClick(View arg0) {
if(arg0==b1)
{
showDialog(DATE_DIALOG_ID);
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, datePickerListener,
year, month,day);
}
return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener
= new DatePickerDialog.OnDateSetListener() {

public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
date.setText(new StringBuilder().append(month + 1)
.append("/").append(day).append("/").append(year).append(" "));
                         }
};
    }


No comments:

Post a Comment