Android:如何在两个不同的EditText字段(开始/结束)中设置时间选择器的时间?

时间:2016-08-07 14:45:29

标签: android events dialog timepicker

我正在尝试获取用户点击EditText StartTime和EndTime的时间。问题是我不知道如何区分EditText处的TimePickerFragment。有什么帮助吗?

public void initializeTime () {
    startTimeEditText = (EditText) findViewById(R.id.startTimeEditText);
    startTimeEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Initialize a new time picker dialog fragment
            DialogFragment dFragment = new TimePickerFragment();
            // Show the time picker dialog fragment
            dFragment.show(getSupportFragmentManager(),"TimePicker");
        }
    });

    endTimeEditText = (EditText) findViewById(R.id.endTimeEditText);
    endTimeEditText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Initialize a new time picker dialog fragment
            DialogFragment dFragment = new TimePickerFragment();

            // Show the time picker dialog fragment
            dFragment.show(getSupportFragmentManager(),"TimePicker");
        }
    });
}

TimePickerFragment.java

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    // Do something with the time chosen by the user
    EditText startTimeEditText = (EditText) getActivity().findViewById(R.id.startTimeEditText);
    EditText endTimeEditText = (EditText) getActivity().findViewById(R.id.endTimeEditText);
    flag = getArguments().getString("Flag");
    Log.v(TAG,flag);

    Toast.makeText(getActivity(), "Toast"+flag, Toast.LENGTH_LONG).show();


    if (startTimeEditText.isActivated()){
        startTimeEditText.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
    }
    else if (endTimeEditText.isActivated()){
        endTimeEditText.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
    }
}

1 个答案:

答案 0 :(得分:0)

TimePickerFragment不应该混淆Activity其余部分的布局:这里最好的方法是将监听器传递给TimePickerFragment。看看TimePicker.setOnTimeChangedListener(...),我知道它不是Fragment,但想法是一样的。

另一种解决方案是使用事件总线(例如包括EventBus library)并在用户选择日期时发布新事件:这样,应用程序的任何组件都可以订阅此事件并相应地执行操作