I am new in android, i want to show the dialog datepicker at the click even on TextView. However, it takes two times to set the date from datepicker on the textview.
TextView XML:
<TextView
android:id="@+id/dateTxtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="MM/DD/YYYY">
Activity Code:
private static final String TAG = "MainActivity";
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting date at the start of the app
mDisplayDate = (TextView) findViewById(R.id.dateTxtView);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCalendar = Calendar.getInstance();
int year = mCalendar.get(Calendar.YEAR);
int month = mCalendar.get(Calendar.MONTH);
int day = mCalendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dateDialog = new DatePickerDialog(
MainActivity.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year,month,day
);
dateDialog.setTitle("Select the date");
dateDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dateDialog.show();
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
Log.d(TAG,"date has been set");
String dateToday = month + "/" + dayOfMonth + "/" + year;
mDisplayDate.setText(dateToday);
}
};
}
});
First, i clicked the textview and show the dialog datepicker and after setting the date and click Ok, there were no value passed to the textview. at the second time, i clicked again and set another date, the date is now pass to the textview. Please help me resolve the problem.
You should declare and define your listener
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
Log.d(TAG,"date has been set");
String dateToday = month + "/" + dayOfMonth + "/" + year;
mDisplayDate.setText(dateToday);
}
};
before you use it in the Picker constructor
DatePickerDialog dateDialog = new DatePickerDialog(
MainActivity.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year,month,day
);