0

您好,我是 android 开发的新手,我正在开发一个应用程序,它需要从 timePicker 获取小时和分钟,所以我确实喜欢这样来获取它:

public class MainActivity extends Activity {

TimePicker timePicker;
 int hour, changedHour;
 int minute, changedMinute;
TextView tv, tv1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) findViewById(R.id.textView1);
    tv1 = (TextView) findViewById(R.id.textView2);
    timePicker = (TimePicker) findViewById(R.id.timePicker1);
    setCurrentTime();
    timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {

        @Override
        public void onTimeChanged(TimePicker arg0, int hourOfDay,
                int minuteOf) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "Time set!",
                    Toast.LENGTH_SHORT).show();
            changedHour = hourOfDay;
            changedMinute = minuteOf;

            tv.setText("Hour of Day is " + changedHour + " and Minute is "
                    + changedMinute);
        }

    });
    tv1.setText("Hour of Day is " + changedHour + " and Minute is "
                    + changedMinute);
}

public void setCurrentTime() {
    // TODO Auto-generated method stub
    final Calendar c = Calendar.getInstance();

    hour = c.get(Calendar.HOUR_OF_DAY);
    minute = c.get(Calendar.MINUTE);

    timePicker.setCurrentHour(hour);
    timePicker.setCurrentMinute(minute);

}`

问题就在这里

changedHour = hourOfDay;
            changedMinute = minuteOf;

            tv.setText("Hour of Day is " + changedHour + " and Minute is "
                    + changedMinute);

我得到了更改的时间,并且当我尝试使用变量时,我将其设置为小时将在hourOfDay = changedHour并且现在在方法之外的分钟相同,问题是它设置为 0 HERE

tv1.setText("Hour of Day is " + changedHour + " and Minute is "
            + changedMinute);

请帮我!

4

1 回答 1

0

在使用 打印它们之前,您从未真正分配给changedHourorchangedMinute变量tv1.setText,因为很可能onTimeChanged到那时还没有触发。出于这个原因,它们的默认值将是 0,因为它们还没有被分配任何其他值。

无论如何,您不能从void函数中返回值。根据定义,void是缺少一种类型。

如何解决这个问题取决于您希望代码如何工作。阻力最小的路径是从内部设置changedHour和设置,例如changedMinutesetCurrentTime

public void setCurrentTime() {
    // TODO Auto-generated method stub
    final Calendar c = Calendar.getInstance();

    hour = c.get(Calendar.HOUR_OF_DAY);
    minute = c.get(Calendar.MINUTE);

    // NEW CODE
    changedHour = hour;
    changedMinute = minute;
    // END NEW CODE

    timePicker.setCurrentHour(hour);
    timePicker.setCurrentMinute(minute);

}

可以通过其他一些机制(返回结构或使用 out 参数)返回小时和分钟,但鉴于您在回调中更新changedHour/MinuteonTImeChanged它可能不适合现有流程。

但是,在重新阅读时,这可能只是因为您在tv1.setText. 您分配给类变量hourminutein setCurrentTime,因此您可以只打印那些而不是changedHourand changedMinute,例如

tv1.setText("Hour of Day is " + hour + " and Minute is "
                + minute);
于 2014-05-15T08:45:54.660 回答