我是新来的。 所以基本上,我正在制作一个应用程序来显示某个区域可用的餐厅,并且在我的 xml 代码中我有多个 TextViews 来通知餐厅是开门还是关门。
我尝试在 onCreate 方法中获取当前日期和时间并更改 textView(如下所示)。
TextView restaurant = (TextView) findViewById (R.id.openTag);
int hour = new Time (System.currentTimeMillis ()).getHour());
if (hour> = 14 && hour <= 19)
restaurant.setText("OPEN");
但这只是应用程序第一次启动。有谁知道该怎么做吗?
最佳答案
好的,经过一些尝试和搜索后,我找到了一个适用于我的代码的解决方案。这是它的一个小例子:
private void updateTextView(ArrayList<Restaurant> restaurants, RestaurantAdapter itemsAdapter) {
Date date = new Date(); // given date
Calendar calendar = Calendar.getInstance(); // creates a new calendar instance
calendar.setTime(date); // assigns calendar to given date
int day = calendar.get(Calendar.DAY_OF_WEEK);
int hour = calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
int minutes = calendar.get(Calendar.MINUTE); // gets hour in 12h format
TextView title = (TextView) findViewById(R.id.openTag);
if(hour>=21) {
restaurants.get(0).changeOpenTag("Closed");
itemsAdapter.notifyDataSetChanged();
}
if (hour>= 9 && hour <= 15) {
title.setText("Lunch");
}
else {
title.setText("Dinner");
}
}
我在 onCreate 方法上添加了:
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
updateTextView(restaurants, itemsAdapter);
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
我不知道这是否是最有效的方法,但至少它工作正常:D
关于java - 如何在应用程序运行时将多个 textView 更改为特定的日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45920628/