从TextView文本设置TimePicker时间

时间:2018-07-12 11:43:54

标签: java android android-studio

我使用this post从TextView创建一个TimePicker。现在,我想显示选择了上一个时间的TimePicker。

因此,我第一次打开TimePicker,并将时间设置为08:15。第二次,我想在TimePicker上显示预设时间08:15,而不是当前小时:分钟。

我认为我需要更改此零件代码:

   @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()));
            }

3 个答案:

答案 0 :(得分:1)

尝试此代码。

public class displayTime extends AppCompatActivity {
TextView textView;
int hour,min;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView=findViewById(R.id.amTvData);
    Calendar mcurrentTime = Calendar.getInstance();
    hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
    min = mcurrentTime.get(Calendar.MINUTE);

    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showTime(hour,min);
         }
    });
}
void showTime(int hours,  int minte){
    TimePickerDialog mTimePicker;
    mTimePicker = new TimePickerDialog(displayTime.this, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
            textView.setText( selectedHour + ":" + selectedMinute);
            hour=selectedHour;
            min=selectedMinute;
        }
    }, hours, minte, false);//Yes 24 hour time
    mTimePicker.setTitle("Select Time");
    mTimePicker.show();

}
}

答案 1 :(得分:1)

或者,@Vinay Rathod's good answer,您可能希望保存在类实例上,不存储任何内容(很多情况可以这样),请尝试以下操作,保存全局变量:

li

答案 2 :(得分:0)

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // get minute and hour from shared preference
        SharedPreferences sharedpreferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
        int hour = sharedpreferences.getInt("hourOfDay", 0);
        int minute = sharedpreferences.getInt("minute", 0);
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // save to preference
        SharedPreferences sharedpreferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();

        editor.putInt("hourOfDay", hourOfDay);
        editor.putInt("minute", minute);
        editor.commit();
    }