2013-06-25 124 views
1

有没有一种方法调用自定义的适配器上notifyDataSetChanged()而无需刷新列表或干扰UI?notifyDataSetChanged()不刷新UI?

我有一个ListView与它后面的自定义适配器,使用客户的对象列表作为它的数据集。当客人通过点击他的名字标记他的出席时,应该在用户界面中显示客人姓名旁边的勾号。这是我能做到的,但是当我打电话notifyDataSetChanged(),名称列表推一路到顶部,大概是因为列表中的“刷新”。

如果我不要请拨notifyDataSetChanged(),但是,当我滚过更新的条目并再次滚动时,刻度消失。这是由于ListView的“回收”视图,据我所知,但它肯定不会让我的工作更容易。

如何调用notifyDataSetChanged()而不是使整个ListView自行更新?

回答

1

更好的位置,在你的客户类中的一个布尔型字段:isPresent。每当用户点击列表项时,您可以使用adapter.getItemAtPosition()获取选定的项目。 将值isPresent更新为true。并显示刻度标记。

在您的适配器类。检查isPresent值。如果标记为true,则显示刻度标记,否则将其隐藏。

这是你如何实现两者。在ListItem上单击显示勾号标记,如果您滚动列表视图并回到同一项目,则您的tickmark显示/隐藏将由适配器保管。

+0

这使得Java的地址引用非常好,并欺骗Android系统认为它仍然是相同的数据集。感谢你的回答。 – Wakka02

1

你可以保留这样

// 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); 
+0

谢谢你的解决方案,它帮助了很多。可惜没有内置的方式来做到这一点,但这会起作用。 编辑:其实,Brijesh的回答是好。并不是说这不行;它当然可以,但是当notifyDataSetChanged()在这一瞬间开始时,它确实会导致UI中的滞后。 – Wakka02

+0

欢迎您:) – blganesh101

0

实际上可能的,如果你不想做一个“选择项”这里是代码

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"); 
         } 
        }); 

       } 
      } 
     }