Using setText with rules regarding the current tim

2019-06-01 19:41发布

问题:

This is my .java file in src:

package com.wao.texttime;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TextTime extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv1 = (TextView) findViewById(R.id.TextView01);
        tv1.setText("Good Morning"); 
        TextView tv2 = (TextView) findViewById(R.id.TextView02);
        tv1.setText("Good Afternoon");
    }
}

I want the TextView to display the different texts depending on what time it is. F.ex. between 08:45-10:45 and so forth. I am very new to coding both for android and in java and I'm trying to figure out how I can make the rules for which text to display. Do you have any suggestions?

回答1:

It might be a bit more complicated. I would probably use the following approach (withh a bit of optimization ofc.)

    TextView textView = (TextView) findViewById(R.id.text);

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());

    cal.set(Calendar.HOUR_OF_DAY, 8);
    cal.set(Calendar.MINUTE, 45);
    cal.set(Calendar.SECOND, 0);

    long morning_start = cal.getTimeInMillis();

    cal.set(Calendar.HOUR_OF_DAY, 10);
    cal.set(Calendar.MINUTE, 0);

    long morning_end = cal.getTimeInMillis();
    long now = System.currentTimeMillis();

    if(now > morning_start && now < morning_end)
    {
        textView.setText("Good morning");
    }
    else
    {
        textView.setText("Have a nice day");
    }


回答2:

Use the time class to get the current time. Then use switch statements or if/else if/else blocks (depending on your exact requirements) to display different texts.



回答3:

You could use a Calender to get the current hour of the day.

int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);