Monday, May 15, 2017

Android Material Time Picker Dialog

Time picker Dialog helps you to pick the time for your application. If you have an option for user pick their time then you can use it. This popup in your layout. SO it's won't take place on your layout. In this post, we learn about how we can use time picker Dialog and pick our time. First, you need to create a class name here TimePickerFragment and extend to DialogFragment and implement TimePickerDialog.OnTimeSetListener ok, Let's start -

public class TimePickerFragment extends DialogFragment implements
  TimePickerDialog.OnTimeSetListener {

}

now override two methods named onCreateDialog and onTimeSet. in onCreateDialog, we add a calendar and get the current time from our calendar and return those values-

@Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {

  //Use the current time as the default values for the time picker
  final Calendar c = Calendar.getInstance();

  int hour = c.get(Calendar.HOUR_OF_DAY);
  int minute = c.get(Calendar.MINUTE);

  //Create and return a new instance of TimePickerDialog
  return new TimePickerDialog(getActivity(), this, hour, minute,
  DateFormat.is24HourFormat(getActivity()));
  }

Note if you want to set a specific time then set on it calendar first and get date same as we do on DatePickerDiolog Ok, let's show again-

SimpleDateFormat format = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);

String timeStr = "10:12 PM"

try {
Date time = format.parse(timeStr);
c.setTime(time);
} catch (ParseException e) {
e.printStackTrace();
}

Note: here I formatted a string into date and set it to the calendar. But you can add directly like this way-

Calendar calendar =Calendar.getInstance();
  
calendar.set(Calendar.HOUR_OF_DAY, 22);
calendar.set(Calendar.MINUTE, 22);

when user set the date then onDateSet will be executed. code is your wish. you get all in an integer. here I save it on shared preference.

@Override
  public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
  String time=hourOfDay+":"+minute;
  SharedPreferences preferences = getActivity().getSharedPreferences("TimeDate", 
                                           Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = preferences.edit();
  editor.putString("Time",time);
  editor.apply();
  }

That's it. we finished up TimePiclerDialog Class. But one this if you want to 12 our clock that's show AM or PM. Then you should modify this code. Because here hourOfDay is shown 24 hours format. Ok now modify the code. If our hourOfDay is greater than 11 then it's must be PM. so we add pm on the string. and subtract from 12 then we get again 12 hours format. Let's move on code-

//Get the AM or PM for current time
        String aMpM = "AM";
        if (hourOfDay > 11) {
            aMpM = "PM";
        }

        //Make the 24 hour time format to 12 hour time format
        int currentHour;
        if (hourOfDay > 11) {
            currentHour = hourOfDay - 12;
        } else {
            currentHour = hourOfDay;
        }

        String time = String.valueOf(currentHour)
                + ":" + String.valueOf(minute) + " " + aMpM;

Not enough for understanding then full methods-

@Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

        //Get the AM or PM for current time
        String aMpM = "AM";
        if (hourOfDay > 11) {
            aMpM = "PM";
        }

        //Make the 24 hour time format to 12 hour time format
        int currentHour;
        if (hourOfDay > 11) {
            currentHour = hourOfDay - 12;
        } else {
            currentHour = hourOfDay;
        }

        String time = String.valueOf(currentHour)
                + ":" + String.valueOf(minute) + " " + aMpM;

        Log.e("TIME is set", time);
        SharedPreferences preferences = getActivity().getSharedPreferences("TimeDate", 
                                                 Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("Time",time);
        editor.apply();
    }

Ok, that's great. Now we use it on on button listener or Click listener on any view.

//set time
        timeTvLabel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerFragment pickerDialog = new TimePickerFragment();
          
                pickerDialog.show(getFragmentManager(), "Time Pick");
            }
        });

That's it. We finish our today coding. Hope it's working.

time picker


 Happy coding.

About Author:

I am Shudipto Trafder,
Since 2015, I write android code. I love to implement new ideas. I use java and also kotlin. Now I am learning Flutter. I love to learn new things and also love to share. And that is the main reason to run this blog.


Let's Get Connected: Facebook Twitter Linkedin Github

No comments :