【问题标题】:change List View without jumping更改列表视图而不跳转
【发布时间】:2016-05-13 11:06:05
【问题描述】:

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

我首先使用此代码设置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 的第一个,我该怎么办?

【问题讨论】:

  • 更新内容时,您希望ListView 在哪里?

标签: java android listview android-arrayadapter


【解决方案1】:

首先使用 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 来将数据设置为 listview。当您向列表视图添加新项目时,请这样做:

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

adapter.notifyDataSetChanged()方法会刷新listview,不会跳转到listview的第一项。

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

【讨论】:

  • 那么请选择这个作为已接受的答案
【解决方案2】:

跳转到第一个元素是ListView 的正常行为。为了识别要滚动到而不是开始的项目,它使用元素的 id。但这只有在 hasStableIds() 返回 true 时才有效。

ArrayAdapter 使用位置作为 id,所以也许正是您正在寻找的。但它从hasStableIds() 返回false。您可以使其与它的自定义子类一起使用。

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

      (-) 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();
      

      所以,现在每当您对 items 数组进行更改时,只需在它之后调用上面的行,您的列表视图将根据更改进行更新。

      希望这会奏效

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多