简体   繁体   English

ListView-滚动加载更多项目

[英]ListView - Load more items with scroll

I need help with listview I am using in a fragment. 我需要片段中使用的Listview的帮助。 The app reads data from an API and my code works fine. 该应用程序从API读取数据,我的代码运行正常。 I load 15 items initially and every next time I load 10 items more. 最初我加载15个项目,下次每次加载10个项目。 However if a request to the API return less than 15 items, it doesn't work. 但是,如果对API的请求返回的内容少于15个,则该请求不起作用。 Also, the app fails when the number of items is not a multiple of 15 or 25 or 35. That is because I load 10 items after the initial setup. 此外,当项目数不是15或25或35的倍数时,应用程序也会失败。这是因为我在初始设置后加载了10个项目。

I need to modify my code for it to work with any number of list items. 我需要修改我的代码才能使其与任何数量的列表项一起使用。

My code is as follows: 我的代码如下:

(ListaFragment.java) -> Here is the ListFragment (ListaFragment.java)->这是ListFragment

    public class ListaFragment extends ListFragment implements OnScrollListener {
    public ListaFragment(){}
    View rootView;

    ListAdapter customAdapter = null;
    ListaLugares listaLugares;    

    // values to pagination
    private View mFooterView;
    private final int AUTOLOAD_THRESHOLD = 4;
    private int MAXIMUM_ITEMS;
    private Handler mHandler;
    private boolean mIsLoading = false;
    private boolean mMoreDataAvailable = true;
    private boolean mWasLoading = false;

    public int ventana = 0;
    public int nInitial;

    private Runnable mAddItemsRunnable = new Runnable() {
        @Override
        public void run() {
            customAdapter.addMoreItems(10);
            mIsLoading = false;

        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_lista, container, false);

        if (container != null) {
            container.removeAllViews();
        }

        ((MainActivity) getActivity()).setBar();


        // read number of places of a category
        listaLugares.readNumberOfPlaces();
        // set
        setNumbersOfItems();
        // read the places a insert in a List
        listaLugares.readPlaces(15, ventana, listaLugares.idCategoria);
        //ventana = ventana + 25;

        return rootView;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listaLugares = ((ListaLugares)getActivity().getApplicationContext());
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final Context context = getActivity();
        mHandler = new Handler();
        customAdapter = new ListAdapter(context, listaLugares.lista);

        mFooterView = LayoutInflater.from(context).inflate(R.layout.loading_view, null);
        getListView().addFooterView(mFooterView, null, false);
        setListAdapter(customAdapter);
        getListView().setOnScrollListener(this);
    }


    public void setNumbersOfItems() {
        if (listaLugares.totalItems > 100) {
            MAXIMUM_ITEMS = 100;
            nInitial = 25;
        } else {
            MAXIMUM_ITEMS = listaLugares.totalItems;
            nInitial = listaLugares.totalItems;
        }
        Log.v("NUMBER OF ITEMS", "Number: " + MAXIMUM_ITEMS + "-"+ nInitial);
    }



    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        //Intent myIntent = new Intent(getActivity(), DetalleActivity.class);
        //myIntent.putExtra("param_id", appState.lista.get(position).id);
        //getActivity().startActivity(myIntent); 
    }


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

         if (!mIsLoading && mMoreDataAvailable) {
             if (totalItemCount >= MAXIMUM_ITEMS) {
                 mMoreDataAvailable = false;
                 getListView().removeFooterView(mFooterView);
             } else if (totalItemCount - AUTOLOAD_THRESHOLD <= firstVisibleItem + visibleItemCount) {
                 ventana = ventana + 10;
                 listaLugares.readPlaces(10, ventana, listaLugares.idCategoria);
                 mIsLoading = true;
                     mHandler.postDelayed(mAddItemsRunnable, 1000);
             }
         }
    }


    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // Ignore
    }


    @Override
    public void onStart() {
        super.onStart();
        if (mWasLoading) {
            mWasLoading = false;
            mIsLoading = true;
            mHandler.postDelayed(mAddItemsRunnable, 1000);
        }
    }


    @Override
    public void onStop() {
        super.onStop();
        mHandler.removeCallbacks(mAddItemsRunnable);
        mWasLoading = mIsLoading;
        mIsLoading = false;
        ventana = ventana;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

(ListAdapter.java) -> Method in adapter class to add more items. (ListAdapter.java)->适配器类中的方法以添加更多项。

    public class ListAdapter extends ArrayAdapter<Lugar> {
Context context;
List<Lugar> values;

ListaLugares listaLugares;

private int mCount = 20;


public ListAdapter(Context context, List<Lugar> values) {
    super(context, R.layout.row, values);
    this.context = context;
    this.values = values;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    row = inflater.inflate(R.layout.row, parent, false);
    TextView firstText = (TextView) row.findViewById(R.id.titulo);
    TextView secondText = (TextView) row.findViewById(R.id.categoria);

    firstText.setText(values.get(position).nombre);
    secondText.setText(values.get(position).categoriaNombre);

    return row;
}


public void addMoreItems(int count) {
    mCount += count;
    notifyDataSetChanged();
}

@Override
public int getCount() {
    return mCount;
}


@Override
public long getItemId(int position) {
    return position;
}

}

I acceded to a previous edited version to see some code. 我加入了先前的编辑版本以查看一些代码。

The first call works because you are starting with a value of 15 on initiaItems and you set it on mCount on the ListAdapter constructor. 第一次调用是有效的,因为您要在mCount上以15 initiaItems并在ListAdapter构造函数的mCount上进行ListAdapter

public ListAdapter(Context context, List<Lugar> values, int count) {
    super(context, R.layout.row, values);
    this.context = context;
    this.values = values;
    this.mCount = count;
}

So when android renders the listview, it acces to the function ListAdapter.getCount() and returns mCount (15). 因此,当android渲染列表视图时,它会访问函数ListAdapter.getCount()并返回mCount (15)。

But when you scroll it can call to 但是当您滚动时,它可以调用

public void addMoreItems(int count, int idCategoria) {
    appState = ((ListaLugares)getContext().getApplicationContext());
    appState.readPlaces(15, mCount, idCategoria);
    mCount += count;
    notifyDataSetChanged();
}

If the number of items returned by the appState.readPlaces is unknown why are you adding a number to mCount mCount += count; 如果未知由appState.readPlaces返回的项目数,为什么要在appState.readPlaces中添加一个数字mCount += count; ?

If appState.readPlaces returns 14 and count is 15 when the listview is rendered it will suppose there are 15+15 items when there are 15+14 so the last item will crash. 如果呈现列表视图时appState.readPlaces返回14且count为15,则当15 + 14时将假定有15 + 15项,因此最后一项将崩溃。

mCount should obtain the length from the object that keeps the data from the API calls, in your case I think it will be appState.lista . mCount应该从保存API调用数据的对象获取长度,在您的情况下,我认为它将是appState.lista

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android sqlite 数据库 - 如何显示列表视图在滚动末尾添加“加载更多项目” - Android sqlite database - how to show listview adding “Load more items” at the end of scroll Android:保存ListView项目并加载/添加更多内容 - Android: Saving ListView items and load/add more 如何使用LoaderManager将更多项目加载到ListView - How to load more items to the ListView with a LoaderManager 使用ListView的事件滚动加载更多数据时出错 - Error when load more data with event scroll of listview 在列表视图中向下滚动时如何加载更多项目? - How can I load more items when scrolling down in listview? 在android中向下滚动时,加载更多项目并在列表底部添加底部 - Load more items and add bottom to the list when scroll down in android 尝试在滚动后自动将新项目加载到ListView时,AbsListView中的setOnScrollListener(…)不适用于(new Runnable(){}) - setOnScrollListener(…) in AbsListView not applicable for (new Runnable(){}) when trying to automatically load new items into ListView after scroll ListView onScroll添加更多项目 - ListView onScroll add more items Android-如何在滚动视图中使用列表视图加载更多项目? - Android-How to Load more items using list view inside scroll view? 将更多数据加载到ListView-Android - Load more data into ListView - Android
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM