无需跳转即可更改列表视图

change List View without jumping

每次我在 Activity 中更改 ListView 时,它都会跳到第一个

我首先使用此代码设置 listView

listView.setAdapter(new ArrayAdapter<String>(this, 
                    R.layout.home_row, R.id.home_row_price, items));

然后我想在列表视图中添加更多数组,所以我使用

 listView.setAdapter(new ArrayAdapter<String>(this, 
                    R.layout.home_row, R.id.home_row_price, items));

再次 new String[] items

但是每次它跳转到 listView 的第一个时我该怎么办?

您可以使用将 String[] 更改为

List<String> items= new LinkedList<String>();

不需要每次都先跳。 在listview中设置adapter时,此时只需要先移动,然后就可以添加、更新或删除列表中的项目,而无需移动到第一个。

为此,请按照以下步骤操作。

(-) First Array of items should be declare at top, means outside of methods.
(-) Also declare instance of adapter also at top, as like
         String[] items;
         ArrayAdapter<> dataAdapter;

(-) Now at first assign values to items and set as adapter.

     like, 
      dataAdapter = new ArrayAdapter(this, R.layout.home_row, R.id.home_row_price, items)
      listView.setAdapter(dataAdapter);

(-) Now, when ever and in any method you want to add, update or delete items from array, perform that operation.

(-) And then, **most important** just write down below line after editing array.

     dataAdapter.notifyDataSetChanged();

因此,现在只要您在项目数组中进行更改,只需在它之后调用上面的行,您的列表视图就会根据更改进行更新。

希望这能奏效

首先使用ArrayList代替String数组来存储数据。 ArrayList 可以动态更改(即它们可以动态更改大小)。 不要为您的列表视图设置匿名适配器,而是像这样:

adapter=new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,arrayList);
lv=(ListView)findViewById(R.id.listView);
lv.setAdapter(adapter);

这里我使用 ArrayList 将数据设置为列表视图。当您向列表视图添加新项目时,请这样做:

arrayList.add(yourData);
...
adapter.notifyDataSetChanged();

adapter.notifyDataSetChanged() 方法将刷新列表视图而不跳转到列表视图中的第一项。

代码中的问题是每次更改数据时,都会为 ListView 设置一个新的适配器。因此 ListView 是 "reset" 而不是 "refreshing".

跳转到第一个元素是 ListView 的正常行为。为了识别要滚动到而不是开始的项目,它使用元素的 id。但这仅适用于 hasStableIds() returns true.

ArrayAdapter 使用位置作为 id,所以也许正是您要查找的内容。但是它 returns false 来自 hasStableIds()。您可以让它与它的自定义子类一起使用。

public class StableArrayAdapter<T> extends ArrayAdapter<T> {
    public StableArrayAdapter(Context ctx, int res, int txt, T[] obj) {
        super(ctx, res, txt, obj);
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }
}