Is there a way to call notifyDataSetChanged()
on a custom adapter without refreshing the list or disturbing the UI?
I have a ListView
with a custom Adapter behind it, using a List of Guest objects as its dataset. When a Guest marks his attendance by tapping on his name, a tick is supposed to appear next to the guest's name in the UI. This I can do, but when I call notifyDataSetChanged()
, the list of names is pushed all the way to the top, presumably because the list "refreshes".
If I don't call notifyDataSetChanged()
, however, the tick disappears when I scroll past the updated entry and scroll back again. This is due to the ListView's "recycling" of Views as I understand, but it sure doesn't make my job any easier.
How would one call notifyDataSetChanged()
without making the entire ListView
refresh itself?
Better to have one boolean field in your Guest Class :isPresent. whenever user taps on list item you can get the selected item using adapter.getItemAtPosition(). update the value isPresent to true. and make show the tick mark.
In your adapter class. check for isPresent value. If it is marked to true then show the tick mark else hide it.
This is how you can achieve the both. Show Tick Mark on ListItem click and if you scroll the listview and come back to the same item you tickmark show/hide will be taken care by Adapter.
you could retain the position like this
// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// ...
// restore
mList.setSelectionFromTop(index, top);
Actually possible if you don't want to make a "selected item" here is the code
public void updateItem(ListView listView, Activity activity) {
if (mData == null) return;
DebugLog.i("A", "firstCell: " + listView.getFirstVisiblePosition() + " lastCell: " + listView.getLastVisiblePosition());
for (int firstCell = listView.getFirstVisiblePosition(); firstCell <= listView.getLastVisiblePosition(); firstCell++) {
final DataItem item = (DataItem) getItem(firstCell); // in this case I put the this method in the Adapter and call it from Activity where the adapter is global varialbe
View convertView = listView.getChildAt(firstCell);
if (convertView != null) {
final TextView titleTextView = (TextView) convertView.findViewById(R.id.item_title);
// here is the most important to do; you have to use Main UI thread to update the view that is why you need activity parameter in the method
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
titleTextView.setText( item + " updated");
}
});
}
}
}
来源:https://stackoverflow.com/questions/17292256/notifydatasetchanged-without-refreshing-the-ui