基于时间android在textview中设置文本

时间:2015-04-07 18:29:37

标签: android

我想在textview中显示一条消息,我现在使用的代码是

mText = (TextView) findViewById(R.id.textView19);

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String str = sdf.format(new Date());

        String[] hr=str.split(":");

        int hr1=Integer.parseInt(hr[0]);

        if(hr1<12)
        {
            mText.setText("it's morning!");
        }else if(hr1>12&& hr1<17)
        {
            mText.setText("it's afternoon!");
        }else if(hr1>17&& hr1<20)
        {
            mText.setText("it's evening!");
        }

但是该代码根本不起作用,它不会在textview中输入任何内容。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您正在创建一个空日期,您需要通过执行以下操作来获取当前时间:

Calendar c = Calendar.getInstance(); // Get current time
int hr1 = c.get(Calendar.HOUR_OF_DAY); // Gets the current hour of the day from the calendar created ( from 1 to 24 )

查看日历文档here