我目前有一个 List View
,它从 ArrayList
获取数据,该数据在 MainActivity
中每隔一定时间更新一次。我想每隔一定的时间更新一次 ListView ,比如说 2 秒。问题是我在 fragment 上有这个适配器,如果我从适配器调用 notifyDataSetChanged();
,只有在 MainActivity
和 MainActivity
之间切换时, View 才会更新。 fragment
。我希望当我在 View 中显示 fragment 时,此 ListView 每 2 秒刷新一次。我尝试在 Adapter 类上运行 TimerTask,但出现异常:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
我想您只能从附加了 fragment 的 MainActivity 中更新 View 。
这就是我运行计时器的方式:
public void setTimer(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
public class RemindTask extends TimerTask {
//Refreshing list view
public void run() {
notifyDataSetChanged();
timer.cancel();
setTimer(2);
}
}
在 MainActivity 上创建适配器实例并每隔一定时间调用 notifyDataSetChanged()
是否安全?
最佳答案
您可以在Fragment中创建一个广播接收器。具有特定的 Action 名称。 让我们说“refresh_data”。 然后从 MainActivity 发送此广播。 示例代码。
public class MyFragment extends Fragment{
private BroadcastReceiver refreshData = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
myAdapter.notifyDataSetChanged();
}
};
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getContext()).registerReceiver(refreshData,
new IntentFilter("refresh_Data"));
}
@Override
public void onPause() {
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(refreshData);
super.onPause();
}
}
每当列表更新时,在 Activity 中调用以下方法
Intent intent = new Intent("refresh_data");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
关于java - 定期更新 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39262762/