[英]Maintain position a ListView after updating
I'm creating a listView that is constantly updated. 我正在创建一个不断更新的listView。 And every time there is an update it comes back to the first item.
每次有更新时,它都会返回到第一项。 I would like to maintain the poistion after every updating.
我想在每次更新后保持状态。
public class Receiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){
results = wifi.getScanResults();
MonAdaptateurDeListe adaptateur = new MonAdaptateurDeListe();
//list1.setAdapter(adaptateur);
if(list1.getAdapter()==null)
{
list1.setAdapter(adaptateur);
}
else
{
adaptateur.notifyDataSetChanged();
//adaptateur.clear();
list1.setAdapter(adaptateur);
}
}
}
}
The root of the problem is because you call setAdapter() again. 问题的根源是因为您再次调用setAdapter() 。 Try to hold a instance of the adapter as a field, during the creation, set it to the ListView and don't touch on the ListView anymore.
尝试将适配器的实例作为字段保留,在创建过程中,将其设置为ListView,然后不再触摸ListView 。
Now, when you receive updates, you just need to call a ' setter ' method on your Adapter with your new data and call: notifyDataSetChanged() ... don't call setAdapter() on every update. 现在,当您收到更新时,只需使用新数据在Adapter上调用“ setter ”方法,然后调用: notifyDataSetChanged() ... 不要在每次更新时都调用 setAdapter() 。
as I said in the comments: 正如我在评论中所说:
ListAdapter adapter = list.getAdapter();
if(adapter == null){
adapter = new MonAdaptateurDeListe();
}else{
// usually here you add the values to the adapter
// for example, in case it's an ArrayAdapter you call `add(value)` on it
adapter.notifyDataSetChanged()
}
that's because the list automatically remember position when you just change the data in the adapter. 这是因为当您仅更改适配器中的数据时,列表会自动记住位置。 But if you're changing the whole adapter, it will reset.
但是,如果您要更改整个适配器,它将重置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.