Returning String from Dialog Fragment back to Acti

2019-01-22 07:39发布

This question already has an answer here:

I have read many posts on this but I can't find any that apply to this case.

I have a time picker dialog and I have put the integer values together in a string and I need to get this string back to the main activity.

This string value will then be used to set the text of a button.

If someone could help me with this it would be most appreciated.

Thank you

Dialog Fragment

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
    @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);

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

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time chosen by the user
        String Time =Integer.toString(hourOfDay) + " : " + Integer.toString(minute);
    }
}

Code

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);


        Button btn = (Button) findViewById(R.id.start_time_button);
        Button.setText(Time);


    }

1条回答
做自己的国王
2楼-- · 2019-01-22 07:55

The preferred method is to use a callback to get a signal from a Fragment. Also, this is the recommended method proposed by Android at Communicating with the Activity

For your example, in your DialogFragment, add an interface and register it.

public static interface OnCompleteListener {
    public abstract void onComplete(String time);
}

private OnCompleteListener mListener;

// make sure the Activity implemented it
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity); 
    try {
        this.mListener = (OnCompleteListener)activity;
    }
    catch (final ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnCompleteListener");
    }
}

Now implement this interface in your Activity

public class MyActivity extends Activity implements MyDialogFragment.OnCompleteListener {
    //...

    public void onComplete(String time) {
        // After the dialog fragment completes, it calls this callback.
        // use the string here
    }
}

Now in your DialogFragment, when a user clicks the OK button, send that value back to the Activity via your callback.

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    String time = Integer.toString(hourOfDay) + " : " + Integer.toString(minute);
    this.mListener.onComplete(time);
}
查看更多
登录 后发表回答