如何在另一个片段中的EditText中获取TimePickerDialog的时间?

时间:2016-01-20 23:05:26

标签: java android android-fragments dialog timepicker

我正在尝试将TimePickerDialog的{​​{1}}时间加到EditTextFinishPostFragment

我现在正在Toast中显示所选时间,但如何在EditText的{​​{1}}中显示数据?

我的onCreateView中的FinishPostFragment:

FinishPostFragment

在onCreateView之外的FinishPostFragment:

timeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // view TimePickerDialog
            showTimeDialog(v);
        }
    });

TimeSettings.java:

public void showTimeDialog(View v){
    TimeDialogFragment tdf = new TimeDialogFragment();
    tdf.show(getFragmentManager().beginTransaction(), "TimePickerFragment");
}

TimePickerDialog.OnTimeSetListener test = new TimePickerDialog.OnTimeSetListener(){
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        time_finish.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
    }
};

TimeDialogFragment:

public class TimeSettings implements TimePickerDialog.OnTimeSetListener {
    Context context;

    public TimeSettings(Context context){
        this.context = context;
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        Toast.makeText(context, "Selected time is hour: " +hourOfDay+ " minute: " + minute, Toast.LENGTH_LONG).show();
    }
}

2 个答案:

答案 0 :(得分:3)

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

Toast.makeText(context, "Selected time is hour: " +hourOfDay+ " minute: " + minute, Toast.LENGTH_LONG).show();
String time = "   "+hourString+"h"+minuteString+"m"+secondString+"s";
    yourTextView.setText(time);

} 

尝试将此文本设置为您的文本视图。

答案 1 :(得分:1)

接近你可能有用的东西如下。请改为FinishPostFragment实施TimePickerDialog.OnTimeSetListener

使用TimeDialaogFragment显示getChildFragmentManager()

tdf.show(getChildFragmentManager().beginTransaction(), "TimePickerFragment");

这样就可以让您在TimeDialogFragment.onCreateView中执行以下操作,将所选时间直接发送到FinishPostFragment

TimePickerDialog.OnTimeSetListener timeSetListener = 
        (TimePickerDialog.OnTimeSetListener) getParentFragment();

dialog = new TimePickerDialog(getActivity(), timeSetListener, hour, minute,
        android.text.format.DateFormat.is24HourFormat(getActivity()));

注意,要使用getParentFragment(),您必须使用支持库或定位API 17 +。