在我的活动中,我有2个TextViews。用户可以点击这些TextView来设置开始和结束日期。我使用的是DatePickerDialog,在点按TextView时会显示该日期。
到目前为止,我的代码:
class DatePickerFragment: DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
return DatePickerDialog(activity, activity as DatePickerDialog.OnDateSetListener, year, month, day)
}
}
class ReportsActivity : AppCompatActivity(), DatePickerDialog.OnDateSetListener {
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
val c = Calendar.getInstance()
c.set(Calendar.YEAR, year)
c.set(Calendar.MONTH, month)
c.set(Calendar.DAY_OF_MONTH, dayOfMonth)
val dateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.time)
// need someway to detect if this is for startDate or endDate
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_report)
startDateTextView.setOnClickListener {
val datePicker = DatePickerFragment()
datePicker.show(supportFragmentManager, "start")
}
endDateTextView.setOnClickListener {
val datePicker = DatePickerFragment()
datePicker.show(supportFragmentManager, "end")
}
}
}
我需要某种方法来检测用户是否从startDateTextView或endDateTextView中打开DatePickerDialog,以便可以相应地设置相应的TextView的文本。
答案 0 :(得分:0)
您可以在textView onClicklistner上设置DateListner。
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
val c = Calendar.getInstance()
c.set(Calendar.YEAR, year)
c.set(Calendar.MONTH, month)
c.set(Calendar.DAY_OF_MONTH, dayOfMonth)
val dateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.time)
// need someway to detect if this is for startDate or endDate
updateDisplay();
updateTextView();
}
private void updateDisplay() {
((TextView) touchedView).setText(
new StringBuilder()
.append(pad(dayOfMonth)).append(".")
.append(pad(month)).append(".")
.append(pad(year)));
}
private void updateTextView() {
((EditText) touchedView).setText(
new StringBuilder()
.append(pad(dayOfMonth)).append(".")
.append(pad(month)).append(".")
.append(pad(year)));
}
在您的片段中添加dateListener
DateListener dateListener = new DateListener(getActivity());
textView.setOnClickListener(dateListener);