不要在notifydatachanged()上移动列表视图位置

时间:2014-04-01 21:45:24

标签: android android-listview

我在我的应用中实现了无限滚动。当我调用notifydatachanged事件时,它会滚动到顶部。

我试图按照Twitter的方式实现无限滚动,即使在请求网络呼叫获取更多数据时滚动到其他位置,也可以保留用户的位置。

我该怎么做?

这是我的listfragment

的一部分
 public void getAds(String productSearch){
        isLoadingMoreAds = true;

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mPullToRefreshLayout.setRefreshing(true);
        } else{
            setListShown(false);
        }
        Services services = Utils.getRESTAdapter();

        String state = "";
        String category = "114";

        anumexServices.getSearch( productSearch , state, category, pagination, new Callback<AdsList>() {
            @Override
            public void success(AdsList adsList, Response response) {
                try{
                    setListShown(true);
                    mPullToRefreshLayout.setRefreshComplete();
                    updateView(adsList.getAd());
                    isLoadingMoreAds = false;
                }catch(IllegalStateException e){
                    Log.e("Exception", "ListFragment ya no existe");
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });

    }


public void updateView(List<Ad> ads){

    Boolean firstPagination = false;

    if(pagination == 0){
        adArrayList.clear();
        firstPagination = true;
    }

    if(ads.size() > 0){

        if(ads.get(ads.size() - 1).getEnd().equals("end")){
            pagination = -1;
        } else{
            pagination += 30;
        }

        adArrayList.addAll(ads);
        showBackgroundMessage(false);

    } else{
        showBackgroundMessage(true);
    }

    listAdapter = new ListAdapter(getActivity(), adArrayList);
    setListAdapter(listAdapter);

    listAdapter.notifyDataSetChanged();

    if(pagination>0 && !firstPagination){
        getListView().setSelectionFromTop(indexList, topList);
    }
}


//Scrolllistener
    @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        int l = visibleItemCount + firstVisibleItem;
        if (l >= totalItemCount && !isLoadingMoreAds && pagination != -1 && wasSuccess) {

            /*get position of listView to set it after notifydatachanged*/

            indexList = view.getFirstVisiblePosition();
            View v = view.getChildAt(0);
            topList = (v == null) ? 0 : v.getTop();

            /* end */

            isLoadingMoreAds = true;

        }
    }

1 个答案:

答案 0 :(得分:1)

每次都不要创建新的ListAdapter。这会将当前列表项重置为第一个。而是仅将新项目添加到列表中,然后调用notifyDataSetChanged()