如何解决如何在 TimePicker 中显示 EditText 的时间?
如何显示已经在 EditText 中的时间,但我必须在时间选择器中显示 EditText 设置的时间。我尝试了下面的代码,但似乎还没有完成。
var dateFormat = ""
if (edittext?.text.toString().isNotEmpty()) {
var date = edittext?.text?.trim().toString()
var spf = SimpleDateFormat("hh:mm aa")
val newDate = spf.parse(date)
spf = SimpleDateFormat("hh:mm")
date = spf.format(newDate)
dateFormat = date
}
val timeSetListener = OnTimeSetListener { timePicker,hour,minute ->
cal.set(Calendar.HOUR_OF_DAY,hour)
cal.set(Calendar.MINUTE,minute)
edittext?.setText(SimpleDateFormat("hh:mm aa").format(cal.time))
}
if (dateFormat.isNotEmpty())
{
try
{
val finalDate: String = dateFormat
val datearr = finalDate.split(":").toTypedArray()
val hh = datearr[0].toInt()
val mm = datearr[1].toInt()
TimePickerDialog(activity,timeSetListener,hh,mm,false).show()
}
catch (e: Exception)
{
e.printstacktrace()
}
}
else
{
try
{
val calendar = Calendar.getInstance()
val yy = calendar[Calendar.HOUR_OF_DAY]
val mm = calendar[Calendar.MINUTE]
TimePickerDialog(activity,yy,false).show()
}
catch (e: java.lang.Exception)
{
e.printstacktrace()
}
}
请检查此代码并提供帮助。另外,我必须用 am 和 pm 来做这件事,所以这不是主要问题。
解决方法
"time" 是你的 EditText 组件试试这个代码...快乐编码:)
time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar selectedHour = Calendar.getInstance();
if (!TextUt.isEmpty(time.getText().toString().trim())) {
Date d = null;
try {
d = sdf2.parse(date.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
selectedHour.setTime(d);
selectedHour.set(Calendar.HOUR_OF_DAY,Integer.parseInt(time.getText().toString().split(":")[0]));
selectedHour.set(MINUTE,Integer.parseInt(time.getText().toString().split(":")[1]));
}
TimePickerDialog dialog = new TimePickerDialog(getContext(),new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker,int hour,int minute) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
try {
Date d = sdf2.parse(date.getText().toString());
c1.setTime(d);
c1.set(HOUR_OF_DAY,hour);
c1.set(Calendar.MINUTE,minute);
c2.setTime(d);
if (TextUtils.isEmpty(time.getText().toString())) {
c2.set(HOUR_OF_DAY,hour);
c2.set(Calendar.MINUTE,minute);
} else {
c2.set(HOUR_OF_DAY,Integer.parseInt(starts[0]));
c2.set(Calendar.MINUTE,Integer.parseInt(starts[1]));
}
Calendar controlCalendar = Calendar.getInstance();
controlCalendar.setTime(d);
controlCalendar.set(HOUR_OF_DAY,hour);
controlCalendar.set(Calendar.MINUTE,minute);
time.setText(String.format("%02d",hour) + ":" + String.format("%02d",minute));
} catch (ParseException e) {
e.printStackTrace();
}
}
},selectedHour.get(HOUR_OF_DAY),selectedHour.get(Calendar.MINUTE),true);
dialog.show();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。