简体   繁体   English

如何在Android Studio中每天自动设置不同的文本到TextView? (将设置为 24 小时,并在下午 12 点自动更改)

[英]How can I automatically set a different text every day to a TextView in Android Studio? (which will set 24 hours and change at 12 pm automatically)

I want to develop quotes of day app project.我想开发日应用程序项目的报价。 for this reason I want to show everyday different quote(aphorism) in the textView. Quote will set 24 hours and change 00:00:01 automaticically.出于这个原因,我想在 textView 中显示每天不同的报价(格言)。报价将设置 24 小时并自动更改 00:00:01。 Someone who uses the application today will see the 1st quote, and the next day, when they open the application, they will see the 2nd quote.今天使用该应用程序的人将看到第一个报价,第二天,当他们打开该应用程序时,他们将看到第二个报价。 3rd day is different, 4th day is different..第三天不一样,第四天不一样。

But my codes doesn't show different quotes.但是我的代码没有显示不同的引号。 every day show day1's quotes.每天显示第一天的报价。

My codes below.我的代码如下。

For example: day1= to be or not to be.例如:day1= 是或不是。 day2= money, money, money.. day2=钱,钱,钱..

My strings.xml我的字符串.xml

<resources>
    <string name="app_name">QuotesApp</string>
    <string-array name="quotes">
        <item>Learn from yesterday, live for today, hope for tomorrow.</item>
        <item>If you want to shine like the sun, first burn like the sun.</item>
        <item>Time never comes again.</item>
        <item>Wealth is the slave of wise man, the master of a fool.</item>
        <item>One thing only I know, and that is that I know nothing.</item>
        <item>A smooth sea never made a skilled sailor.</item>
    </string-array>
</resources>

My Mainactivity.java我的主要活动.java

TextView dailyGreetings;
    String[] mTestArray;
    DateFormat dateFormat= new SimpleDateFormat("dd-MM-yyyy");
    Date date=new Date();
    SharedPreferences preferences_Shared, text_Shared;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        dailyGreetings=findViewById(R.id.dailyGreetings);
        mTestArray=getResources().getStringArray(R.array.quotes);
        preferences_Shared=this.getSharedPreferences("PREFERENCE",MODE_PRIVATE);
        text_Shared=this.getSharedPreferences("TEXT",MODE_PRIVATE);

        Calendar c=Calendar.getInstance();
        int timeofDay=c.get(Calendar.DAY_OF_MONTH);

        if (timeofDay>=1){
            if (preferences_Shared.getBoolean("isFirstRun", true)){
                dailyGreetings.setText(mTestArray[(0) %(mTestArray.length)]);
                saveDate();
            }else{
                if (!Objects.equals(preferences_Shared.getString("Date", ""), dateFormat.format(date)))
                {
                    int idx=new Random().nextInt(mTestArray.length);
                    dailyGreetings.setText(mTestArray[idx]);
                    text_Shared.edit().putString("TEXT", dailyGreetings.getText().toString()).apply();
                    saveDate();
                }
                else {
                    dailyGreetings.setText(text_Shared.getString("TEXT", ""));
                }
            }
        }
    }

    private void saveDate() {
        preferences_Shared=this.getSharedPreferences("PREFERENCE",MODE_PRIVATE);
        editor=preferences_Shared.edit();
        editor.clear();
        editor.putString("Date",dateFormat.format(date));
        editor.apply();
    }

Your condition is to check if isFirstRun is true, and it will always default to true since you never set it to false.您的条件是检查isFirstRun是否为真,并且它将始终默认为真,因为您从未将其设置为假。 That's why you're always getting the first quote.这就是为什么您总是获得第一个报价。

I see some bugs in your else branch as well.我在你的 else 分支中也看到了一些错误。 Whenever the app is opened more than once on the same day, it's going to hit that inner else branch and show nothing.每当该应用程序在同一天打开不止一次时,它就会到达内部的其他分支并且什么都不显示。 And you're using a formatted String date to store, which is error-prone, especially if you don't specify a Locale.并且您使用格式化的 String 日期来存储,这很容易出错,尤其是在您未指定 Locale 的情况下。 Dates and times should always be stored as Longs.日期和时间应始终存储为 Longs。

I think the simplest way to do this is to get the current date, count how many days it has been since some constant date (the epoch suffices), and then use the remainder operator with the number of available quotes to get a new quote day by day.我认为最简单的方法是获取当前日期,计算自某个固定日期(纪元就足够)以来已经过了多少天,然后使用余数运算符和可用报价的数量来获得新的报价日按天。

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
    setContentView(R.layout.activity_main)

    val dailyGreetings: TextView = findViewById(R.id.dailyGreetings)
    val quotes = resources.getStringArray(R.array.quotes)
    val daysSinceEpoch = LocalDate.now().toEpochDay()
    val quoteIndex = (daysSinceEpoch % quotes.size).toInt()
    dailyGreetings.text = quotes[quoteIndex]
}

If you really need to pick a random quote every day instead of going through them in your defined order, with the risk that this sometimes mean the same quote gets randomly picked two or more days in a row, then you can use a Random with the date as a seed, so the same date will always get the same random value:如果你真的需要每天选择一个随机报价而不是按照你定义的顺序浏览它们,这有时意味着同一报价连续两天或更多天被随机选择的风险,那么你可以使用 Random 与日期作为种子,因此相同的日期将始终获得相同的随机值:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
    setContentView(R.layout.activity_main)

    val dailyGreetings: TextView = findViewById(R.id.dailyGreetings)
    val quotes = resources.getStringArray(R.array.quotes)
    val daysSinceEpoch = LocalDate.now().toEpochDay()
    val random = Random(daysSinceEpoch)
    dailyGreetings.text = quotes[random.nextInt(quotes.size)]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Android 中每天上午 12 点到下午 6 点之间安排一些工作,间隔为 60 分钟? - How can I schedule some work every day between 12 am to 6 pm with a 60 minute interval in Android? 在Android中每24小时自动实例化活动中的功能 - Instantiate a function in an activity automatically for every 24 hours in Android 当我在Android Studio或IntelliJ IDEA中更改方法签名时,如何将JavaDoc设置为自动更新 - How to set JavaDoc to update automatically when I change the method signature in Android Studio or IntelliJ IDEA TextView 高度随 android 中的不同文本自动变化 - TextView height changing automatically with different text in android 如何在android studio上的增强现实应用程序中在Textview中动态设置文本 - how can I dynamically set text in Textview in augmented reality application on the android studio 如何使用AM&PM在时间选择器中设置12小时格式? - How to set 12 hours format in time picker with AM & PM? 如何在第二天自动获取 Unix 时间戳? - How can I get Unix Timestamp automatically for every next day? 如何在 Android Studio 中每 24 小时重置一次数据结构? - How do I reset a data structure every 24 hours in Android studio? 如何在Android Studio中为每个设备设置标准布局 - How can I set a standard layout for every device in android studio 如何将textview文本设置为用户每次按下按钮时输入的名称? - How can i set textview text to names that the user input every time i hit a button?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM