'MaterialTimePicker fragment not showing up
New to android development. I want to take a time input from user using MaterialTimePicker and show the time in a TextField. MaterialTimePicker fragment is activated using a onClickListener on a Button. Also I'm developing in java and I'm not sure the documentation on material.io website is for java or kotlin.
btnobj.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
timepicker();
}
});
void timepicker(){
MaterialTimePicker picker = new MaterialTimePicker.Builder()
.setTimeFormat(TimeFormat.CLOCK_24H)
.setTitleText("Select Start Time")
.setHour(12)
.setMinute(10)
.build();
picker.show(getSupportFragmentManager(), "starttime");
txtfieldobj.setText(String.valueOf(picker.getHour())+" : "+String.valueOf(picker.getMinute()));
}
ERROR: Currently when I run this code after I click the button a blank page appears for a second and then it goes back to the parent activity.
Solution 1:[1]
I tried your example, and your problem is that you need to delete this line
txtfieldobj.setText(String.valueOf(picker.getHour())+" : "+String.valueOf(picker.getMinute()));
because it crashes the app with this 
And if you want to show the date and time after clicking OK, here the code:
private final SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a", Locale.getDefault());
void timepicker() {
MaterialTimePicker picker = new MaterialTimePicker.Builder()
.setTimeFormat(TimeFormat.CLOCK_24H)
.setTitleText("Select Start Time")
.setHour(12)
.setMinute(10)
.build();
picker.addOnPositiveButtonClickListener(dialog -> {
int newHour = picker.getHour();
int newMinute = picker.getMinute();
DashBoardActivity.this.onTimeSet(newHour, newMinute);
});
picker.show(getSupportFragmentManager(), "starttime");
}
private void onTimeSet(int newHour, int newMinute) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, newHour);
cal.set(Calendar.MINUTE, newMinute);
cal.setLenient(false);
String format = formatter.format(cal.getTime());
txtfieldobj.setText(format);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
