Search code examples
androidlistviewandroid-recyclerviewtimepicker

Android Recycler View Adapter with TimePicker


I have a Fragment with a RecyclerView where the user can introduce one or more time zones, choosing starting and ending time.

When the user taps on every hour, appears the time picker:

When the hour is selected, I want to change the text hour to the one selected by the user. I show the timePicker from the RecyclerView adapter but I don't know how to pass from onTimeSet to modify the textView of the hour. As far as I know it has to be inside RecyclerView adapter.


Solution

  • Finally I found the solution. All of this happen inside RecyclerView Adapter. I added an onClick listener to the textView. Then I pass the view when I create the Dialog Fragment.

    Inside the onBindViewHolder:

    horarioViewHolder.mFromTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    DialogFragment newFragment = new TimePickerFragment(v);
                    newFragment.show(((ChefAltaUnoActivity)mContext).getSupportFragmentManager(), "timePicker");
    
                }
            });
    

    Inside TimePickerFragment:

    public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
    
    
        private View mView;
    
        public  TimePickerFragment(View view) {
            mView = view;
        }
    
    
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current time as the default values for the picker
    
    
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);
    
    
            TimePickerDialog timePicker = new TimePickerDialog(getActivity(), R.style.CustomTimePickerDialogTheme, this, hour, minute,
                    DateFormat.is24HourFormat(getActivity()));
    
    
            // Create a new instance of TimePickerDialog and return it
            return timePicker;
        }
    
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    
    
            ((TextView) mView).setText("format the time text as you want.");
    
        }
    
    }
    

    Hope it helps someone else.