Android - 防止在notifyDataSetChanged()上滚动到底部

Íca*_*reu 4 android

我正在构建一个聊天应用程序,我需要向上滚动以加载更多数据.但是当我把notifyDataSetChanged()我的ListView卷轴调到底部时.

我的ListView:

    <ListView
        android:id="@+id/list_messages"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:transcriptMode="alwaysScroll"
        android:stackFromBottom="true">
    </ListView>
Run Code Online (Sandbox Code Playgroud)

BaseAdapter是这样的:

public class CompleteListAdapter extends BaseAdapter {  
      private Activity mContext;  
      private List<String> mList;  
      private LayoutInflater mLayoutInflater = null;  
      public CompleteListAdapter(Activity context, List<String> list) {  
           mContext = context;  
           mList = list;  
           mLayoutInflater = (LayoutInflater) mContext  
                     .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
      }  
      @Override  
      public int getCount() {  
           return mList.size();  
      }  
      @Override  
      public Object getItem(int pos) {  
           return mList.get(pos);  
      }  
      @Override  
      public long getItemId(int position) {  
           return position;  
      }  
      @Override  
      public View getView(int position, View convertView, ViewGroup parent) {  
           View v = convertView;  
           CompleteListViewHolder viewHolder;  
           if (convertView == null) {  
                LayoutInflater li = (LayoutInflater) mContext  
                          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
                v = li.inflate(R.layout.list_layout, null);  
                viewHolder = new CompleteListViewHolder(v);  
                v.setTag(viewHolder);  
           } else {  
                viewHolder = (CompleteListViewHolder) v.getTag();  
           }  
           viewHolder.mTVItem.setText(mList.get(position));  
           return v;  
      }    }    class CompleteListViewHolder {  
      public TextView mTVItem;  
      public CompleteListViewHolder(View base) {  
           mTVItem = (TextView) base.findViewById(R.id.listTV);  
      }    
}
Run Code Online (Sandbox Code Playgroud)

如何防止列表滚动到底?

Íca*_*reu 9

这很容易!只需更改ListView上的transcriptModeto即可normal

<ListView
    android:id="@+id/list_messages"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:transcriptMode="normal"
    android:stackFromBottom="true">
</ListView>
Run Code Online (Sandbox Code Playgroud)

并保持第一项List以获得它的位置notifyDataSetChanged()

// Get last item object
Item itemPlaceHolder = itemsList.get(0);

//  {  Retrieve new items here  }

adapter.notifyDataSetChanged(); // <-- Update the adapter

// Get position of the item
int index = itemsList.indexOf(itemPlaceHolder);

list_view.clearFocus(); 
list_view.setFocusable(true);

// Set position of the scroll
list_view.setSelection(index + 1);
Run Code Online (Sandbox Code Playgroud)

瞧!