Add Multiple DatePicker in same activity Android (JAVA)
If you are absolutely new to the Android platform and have been building an application while learning the development process.
Currently, If you are working on an activity in which you need to deploy 2 date pickers. One is a "Start Date" and the other is an "End date".
Currently, If you are working on an activity in which you need to deploy 2 date pickers. One is a "Start Date" and the other is an "End date".
This article will help you
You have to use a boolean flag to know which text view to fill with the picked date from the date picker dialog. Below, a visual representation of the code.
public class TimeSheetPage extends AppCompatActivity implements DatePickerDialog.OnDateSetListener { // To Check Which datepicker is clicked private boolean isStarted = true; TextView txtStart, txtEnd; Button btnSearch;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_time_sheet_page); txtStart = findViewById(R.id.txt_ts_start); txtEnd = findViewById(R.id.txt_ts_end); btnSearch = findViewById(R.id.btn_ts_search);
//Start Date txtStart.setOnClickListener(v -> { showDatePickerDialog(); isStarted = true; }); //End Date txtEnd.setOnClickListener(v -> { showDatePickerDialog(); isStarted = false; }); //Search Button btnSearch.setOnClickListener(v -> { }); } // To datepicker dialog call public void showDatePickerDialog() { DatePickerDialog datePickerDialog = new DatePickerDialog( this, this, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); datePickerDialog.show(); }
@Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { String date = month + "/" + dayOfMonth + "/" + year; if (isStarted) { txtStart.setText(date); } else { txtEnd.setText(date); } }}
you have to implement DatePickerDialog.OnDateSetListener
so that you can Override onDateSet
Then just add a check on isStarted and you good to go...
Thank you
No comments: