Search code examples
javaandroidandroid-fragmentsfragmentandroid-dialogfragment

How to fix show method in FragmentDialog


I write this code to show time in my project when I run the app stop working. However, when I delete show method program works without anything shown when I press the Button

any help please

this is the code

public class AlarmFragment extends Fragment implements 
    TimePickerDialog.OnTimeSetListener{
    private Button clockBtn;
    private TextView time;
 public AlarmFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_alarm, container, false);
    time = view.findViewById(R.id.alarm_time);
    clockBtn= view.findViewById(R.id.clock_btn);
    clockBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            DialogFragment clock= new TimeClock();
              ///////////show method /////////
             clock.show(getActivity().getSupportFragmentManager(),"Time Picker");


        }
    });
    return view;
}
  @Override
     public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        time.setText("Time:" + hourOfDay +" : "+minute);
      }}

this is TimeClock Fragment

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import java.util.Calendar;

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

Edit:- so I changed the return statement above, then it works.But onTimeSet method in AlarmFragment did not executed I did it as follow:-

Activity activity = new AlarmFragment().getActivity();

        return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener)activity, hour, minute, android.text.format.DateFormat.is24HourFormat(getActivity())); 

Solution

  • In the Activity that hosts your AlarmFragment, you must implement TimePickerDialog.OnTimeSetListener.

    For example:

    public class MainActivity implements TimePickerDialog.OnTimeSetListener {
    
        ...
    
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            Toast.makeText(this, "chosen hour of day: " + hourOfDay, Toast.LENGTH_LONG).show();
        }
    }