首次尝试时,Android Java时间选择器侦听器无法检索小时和分钟

时间:2015-03-01 10:15:15

标签: java android timepicker

我无法获取用户为我的Android应用程序设置的分钟和小时数。问题是,当我第一次尝试在public void onTimeSet...函数中设置时间时,我的btn(hour+":"+minutes)显示0:0,但如果我第二次尝试,btn能够显示时间。我不确定是什么问题或我的编码逻辑是错误的...任何人都可以帮我跟踪它? 这是我的代码:

RelativeLayout rlSun = (RelativeLayout)rootView.findViewById(R.id.sundayRelativeLayout);
rlSun.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        //openTimePickerDialog(true);
        Calendar currenttime = Calendar.getInstance();

        final TimePickerDialog  timePickerDialog = new TimePickerDialog(
                getActivity(), //because this class extends fragment
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay,
                                          int minute) {
                        // Get the selected time
                        hour =hourOfDay;
                        minutes = minute;
                    }       
                 }, 
                 currenttime.get(Calendar.HOUR_OF_DAY), 
                 currenttime.get(Calendar.MINUTE), 
                 false);
        timePickerDialog.setTitle("Set Time");  
        timePickerDialog.setButton(
              DialogInterface.BUTTON_POSITIVE,
              "Set",
              new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int which) {
                      if (which == DialogInterface.BUTTON_POSITIVE) {
                          RelativeLayout rl = (RelativeLayout)rootView.findViewById(R.id.sundayRelativeLayout);
                          Button btn = new Button(getActivity());
                          btn.setText(hour+":"+minutes);
                          RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,60);
                          rl.addView(btn,newParams);
                      }
                  }
              });
              timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                  "Cancel",
                  new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which){
                            if (which == DialogInterface.BUTTON_NEGATIVE){
                                timePickerDialog.cancel();
                            }
                  }
              });
              timePickerDialog.show();

其他信息: 我已在课堂外声明hour and minutes

1 个答案:

答案 0 :(得分:0)

在打开对话框之前,您需要将hourminutes变量初始化为当前时间。