cod*_*441 29 java android android-listview
我正在尝试实现无限滚动列表视图,但是当我调用notifyDataSetChanged()整个列表刷新时,滚动位置将返回到顶部.
这是正常行为吗?如何才能简单地添加添加的项目而不刷新并保持滚动位置?
Yar*_*arh 64
这种行为不正常.没有看到你的代码我可以建议如下:
1)您没有notifyDataSetChanged()从UI线程调用.正确的方法:
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
Run Code Online (Sandbox Code Playgroud)
2)你不小心打电话给 adapter.notifyDataSetInvalidated();
3)在您的适配器中,您重写该adapter.notifyDataSetChanged();方法并添加指令以转到顶部
4)如果您使用列表填充适配器 - 每次都提供新列表,因此适配器设置会刷新.您应始终提供相同的列表.但是,您可以根据需要更改它.如果您正在重置列表,请使用list.clear而不是list = new ArrayList();
这是我的适配器的一个例子:
public class Adapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public MediaItemAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.item_composer, null);
}
TextView title = (TextView) vi.findViewById(R.id.item_title); // title
TextView price = (TextView) vi.findViewById(R.id.price);
return vi;
}
}
Run Code Online (Sandbox Code Playgroud)
调用适配器:
List myList = new ArrayList<HashMap<String, String>>();
Adapter ma = new Adapter(this, myList);
Run Code Online (Sandbox Code Playgroud)
在适配器初始化之前,myList可以为空.
然后用我的列表做一些操作:
myList.add(someElement);
ma.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)
如果你需要删除所有项目:
myList.clear();
ma.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)
这样的实现是无穷无尽的,我看到了超过15000个元素没有任何问题.
在我的情况下,问题是我ListView.setAdapter(adapter)每次设置新数据时都会调用,这也会重置位置并且视图跳到顶部.
删除冗余setAdapter(...)呼叫为我修复了它.
小智 6
你可以用另一种方式来做,就像这样
int position = scrollView.getSelectedItemPosition();
notifyDataSetChanged();
scrollView.setSelection(position);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53753 次 |
| 最近记录: |