仅双击Android TextView更新

时间:2015-08-28 17:05:06

标签: android textview uitextview

我从时间选择器对话框中获取时间并将其转换为字符串格式。然后我使用setText方法将其设置为TextView。问题是它设置了字符串,但只有在单击设置时间按钮不少于两次之后。一次尝试,TextView仍然是空的。任何建议?我希望它在textview中第一次单击显示数据

beginTime.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


                    openTimePicker(true);

                    onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int hour, int min){
                            Calendar calnow = Calendar.getInstance();

                            Calendar calset = (Calendar) calnow.clone();
                            calset.set(Calendar.HOUR_OF_DAY, hour);
                            calset.set(Calendar.MINUTE, min);

                            SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
                          time=sdf.format(calset.getTime());
                            beginTime.setText(time);




                        }
                    };




        }

    });

private void openTimePicker(boolean is24r){

    Calendar cal = Calendar.getInstance();

    TimePickerDialog timePicker = new TimePickerDialog(this, onTimeSetListener,cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE),is24r);
    String begin = "TIME";
    timePicker.setTitle(begin);
    timePicker.show();



}

2 个答案:

答案 0 :(得分:0)

您应该看到与您单击的按钮关联的侦听器。你需要的是setOnCLickListener

答案 1 :(得分:0)

这是因为在openTimePicker中,您创建了TimePickerDialog

TimePickerDialog timePicker = new TimePickerDialog(this, onTimeSetListener,cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE),is24r);

需要onTimeSetListener,但仅在调用openTimePicker后创建。

所以,在第一次运行中,你创建了一个没有监听器的对话框,只在第二次运行或之后,它被正确设置。

快速修复:只需按此顺序颠倒顺序

                onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int hour, int min){
                        Calendar calnow = Calendar.getInstance();

                        Calendar calset = (Calendar) calnow.clone();
                        calset.set(Calendar.HOUR_OF_DAY, hour);
                        calset.set(Calendar.MINUTE, min);

                        SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
                      time=sdf.format(calset.getTime());
                        beginTime.setText(time);




                    }
                };
                openTimePicker(true);