TimePickerDialog in Sketchware


To create a TimePickerDialog in Sketchware android project follow the steps given below.

1. In VIEW area of your sketchware android project, insert a LinearH and inside it insert a TextView textview1, and a Button button1.
For textview1 write text as '00:00'.

2. Create a more block extra.

3. In the more block extra use add source directly block and put following code.
}

public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute, android.text.format.DateFormat.is24HourFormat(getActivity()));
}

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
TextView textview101 = getActivity().findViewById(R.id.textview1);
textview101.setText(hourOfDay + ":" + minute);
}

* This code defines a DialogFragment called TimePickerFragment, which has onCreateDialog(Bundle) and onTimeSet(TimePicker, int, int) methods.
* The current time received from the Calendar is used as default values for the Time picker.
* To display the time chosen by the user in textview1, a new TextView textview101 is defined from the id of textview1. This textview101 displays the chosen time. This step is necessary and we cannot display the time directly in textview1 because that causes IllegalStateException in newer versions of Android.
* In the code above, following part
TextView textview101 = getActivity().findViewById(R.id.textview1);
textview101.setText(hourOfDay + ":" + minute);
can also be written as
((TextView)getActivity().findViewById(R.id.textview1)).setText(hourOfDay + ":" + minute);

4. In button1 onClick event use an add source directly block and put following code.
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");

5. Save and run the project. Now on clicking the Button TimePickerDialog will appear from which user can select time. The time selected is displayed in the TextView.

Comments

  1. Как добавить секунды?

    ReplyDelete
  2. I need seconds. Help me please.

    ReplyDelete
  3. I was trying to add 2 timepickerdialogs but an error occurs. It says "TimePickerDialog.OnTimeSetListener duplicate nested type TimePickerFragment". Please reply and say how to solve it.

    ReplyDelete
    Replies
    1. You need to change the name of the second time picker because it is duplicated hope it helps

      Delete
  4. How to return time in 12 hour format

    ReplyDelete

Post a Comment

Popular posts from this blog

Simple car racing android game in Sketchware

How to enable upload from webview in Sketchware?

Enable Fullscreen for Youtube videos in WebView

Creating a Drawing View in Sketchware

List of Calendar Format symbols valid in Sketchware