开发者

Using setText with rules regarding the current time

开发者 https://www.devze.com 2023-01-27 13:20 出处:网络
This is my .java file in src: package com.wao.texttime; import android.app.Activity; import android.os.Bundle;

This is my .java file in src:

package com.wao.texttime;

import android.app.Activity;
import android.os.Bundle;
import andr开发者_运维知识库oid.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?


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");
    }


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.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消