在TextView中显示时间并不断更新的最佳方法是什么?我目前拥有的代码不会更新现有的TextView,而是在我的布局Example内创建一个新的TextView。
我有以下代码:Boss.java BossAdapter.java
public String[] getTime(){
String[] time_array = new String[6];
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("HH-mm-ss");
String formattedDate = df.format(c.getTime());
for(int i = 0; i < 6; i++){
time_array[i] = formattedDate;
}
return time_array;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
bossView = (TextView) findViewById(R.id.boss_time);
boss_title = getResources().getStringArray(R.array.boss_array);
adapter = new BossAdapter(getApplicationContext(), R.layout.boss_layout);
listView.setAdapter(adapter);
handler = new Handler();
Runnable update = new Runnable() {
@Override
public void run() {
bossTime = getTime();
int i = 0;
for (String boss : boss_title) {
Boss bossObject = new Boss(boss_icon[i], boss, bossTime[i]);
adapter.add(bossObject);
i++;
}
handler.postDelayed(this , 1000);
}
};
handler.postDelayed(update, 10);
}
答案 0 :(得分:0)
此处,代码修复程序在下面进行了注释和解释,
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
bossView = (TextView) findViewById(R.id.boss_time);
boss_title = getResources().getStringArray(R.array.boss_array);
adapter = new BossAdapter(getApplicationContext(), R.layout.boss_layout);
listView.setAdapter(adapter);
bossTime = getTime();
int i = 0;
// Moved our object creation here, so that it should only be done once.
for (String boss : boss_title) {
Boss bossObject = new Boss(boss_icon[i], boss, bossTime[i]);
adapter.add(bossObject);
i++;
}
handler = new Handler();
Runnable update = new Runnable() {
@Override
public void run() {
bossTime = getTime();
int count = adapter.getCount()
for (int i = 0; i < count; i++) {
((Boss) adapter.getItem(i)).setBoss_time(bossTime[i]); // Re-set time
}
adapter.notifyDataSetChanged(); // Notify our update
handler.postDelayed(this , 1000);
}
};
handler.postDelayed(update, 10);
}