【问题标题】:Android Textview Change while time get changeAndroid Textview Change while time get change
【发布时间】:2017-02-02 10:51:38
【问题描述】:

我是 android 新手,我正在尝试学习一些新东西。

当时间改变时,我想改变我的textview。 例如,如果在上午 12 点到下午 12 点之间,则应显示“早安”,否则应显示“晚安”

我试过的代码如下..

SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
String formattedDate = df.format(c.getTime());

Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();

if(formattedDate.equals("00:00:00")&&formattedDate.equals("12:00:00")){
    textView.setText("good morning");
}else{
    textView.setText("good Evening");
}

此代码的问题在于,如果您在上午 12 点或下午 12 点打开此应用程序,它将显示“早上好”文本,如果不是,则显示“晚安”。 我想要的是文本应该在上午 12 点到下午 12 点之间显示早安,其余时间应该显示晚安..

如果您能提供帮助,请提前致谢..:)

【问题讨论】:

标签: android android-studio textview android-timer


【解决方案1】:
    Calendar c = Calendar.getInstance();
    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss a");
    String formattedDate = df.format(c.getTime());

    if (formattedDate.contains("AM")) {
        textView.setText("Good Morning");
    } else {
        textView.setText("Good Evening");
    }

【讨论】:

  • 如何添加下午好问候语?如果时间在下午 12:00 到下午 4:00
【解决方案2】:

检查下面的代码

public static String Convert24to12(String time)
{
String convertedTime ="";
try {
    SimpleDateFormat displayFormat = new SimpleDateFormat("hh:mm a");
    SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm:ss");
    Date date = parseFormat.parse(time);        
    convertedTime=displayFormat.format(date);
    System.out.println("convertedTime : "+convertedTime);
} catch (final ParseException e) {
    e.printStackTrace();
}
return convertedTime;
//Output will be 10:23 PM
}

这里你只检查这个条件

if(Convert24to12(formattedDate).contains("AM")){
   textView.setText("good morning");
}else{
   textView.setText("good Evening");
}

【讨论】:

    【解决方案3】:
    Calendar calendar = Calendar.getInstance();
    
    SimpleDateFormat sdf = new SimpleDateFormat("HH");
    
    int temp = Integer.parseInt(sdf.format(calendar.getTimeInMillis()));
    
    if(temp > 12)
    {
        System.out.println("Good Evening");
    }
    else
    {
        System.out.println("Good Morning");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-16
      • 2016-11-17
      • 1970-01-01
      • 2012-08-26
      • 2019-10-14
      • 2016-11-15
      • 2023-02-09
      • 2012-01-15
      相关资源
      最近更新 更多