且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在今天日期未设置LocalDate值

更新时间:2023-10-14 23:36:10

您的代码存在的问题是循环的7次迭代将为所有按钮分配提示,因此您将对每个按钮进行7个分配,共进行49个分配,增加每个分配后的日期,以达到这些错误的日期。

因此,结果是您看到从上次迭代分配的值显然是错误的。

在每次迭代中将1分配给1个按钮,如下所示:

The problem with your code is that in each of the 7 iterations of the loop you are assigning the hints to all the buttons, so you are doing 7 assignments to each button, total 49 assignments, increasing the date after each assignment, so you reach these incorrect dates.
So the result is that you see the values assigned from the last iteration which are obviously wrong.
Do 1 assignment to 1 button in each iteration like this:

DateTimeFormatter dateFormater = DateTimeFormatter.ofPattern("d");
ZoneId zone = ZoneId.of("Asia/Jakarta");
LocalDate date = LocalDate.now(zone);
int amount = 1;
int buttonCount = 7;
for (int i = 0; i < buttonCount; i++){
    int buttonId = getResources().getIdentifier("hari_" + (i + 1), "id", getPackageName()); 
    Button button = (Button) findViewById(buttonId);
    button.setHint(date.format(dateFormater));
    date = date.plusDays(amount);
}

使用此行:

int buttonId = getResources().getIdentifier("hari_" + (i + 1), "id", getPackageName());

您将获得每个按钮的整数 id 并使用以下行:

you get the integer id of each button and with this line:

Button button = (Button) findViewById(buttonId);

您将获得一个引用按钮的变量。

you get a variable referencing the button.