我试图实现一个由SwitchCompat打开的时间选择器,所以当我启用该选项时,时间选择器会显示出来,可以正常工作,但是如果我按“取消”或“后退”按钮,或者只是按时间选择器之外,开关保持在“开”位置,并且当我没有在“时间选择器”中选择时间时,我希望它回到“关”。以为onCancel方法可能会有所帮助,但没有效果,或者我在实现它时犯了一些错误,有相关的代码:

public class Settings extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, TimePickerDialog.OnDismissListener, TimePickerDialog.OnCancelListener {
    private EditText textLastHour;
    private KeyListener keyListener;
    private SwitchCompat hourSwitch;

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

        textLastHour = findViewById(R.id.finalHourText);
        textLastHour.setKeyListener(null);
        textLastHour.setHint("Option not selected");

        hourSwitch = findViewById(R.id.switch_hour);

        hourSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    DialogFragment timePicker = new TimePickerFragment();
                    timePicker.show(getSupportFragmentManager(), "time picker");

                } else {
                    textLastHour.setText("");
                }
            }
        });
    }


    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        textLastHour = findViewById(R.id.finalHourText);
        textLastHour.setText("Final alarm at: " + hourOfDay + ":" + minute);
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        hourSwitch.setChecked(false);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        hourSwitch.setChecked(false);
    }
}


我已经尝试了onDismissonCancel,但都没有在这里工作,如果您取消了时间选择器,是否有任何解决方案可以使Switch返回原始位置?我在标签中添加了DatePicker,因为我认为它可以与TimePicker相同的解决方案。

我的TimePickerFragment课:

public class TimePickerFragment extends DialogFragment {

    @NonNull
    @Override
    public Dialog onCreateDialog(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, DateFormat.is24HourFormat(getActivity()));
    }
}

最佳答案

它实际上比我想的简单,您只需要添加一个解雇侦听器并相应地更改您的ui / logic

TimePickerDialog dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

    }
}, 10, 10, true);

dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
    @Override
    public void onCancel(DialogInterface dialog) {
        Toast.makeText(MainActivity.this, "dismissed", Toast.LENGTH_LONG).show();
    }
});

dialog.show();


您可以使用标准的TimePickerDialog

编辑:将除onCreate()之外的所有内容放入dialog.show()dialog.show()进入Switch中的ifChecked

09-15 16:04