How to implement OnScrollListener to a listview??

2020-03-03 09:40发布

i am getting 500 records from server..i want to display 10 items in a listview and when listview reaches end i need to load another 10 and so on.. I have seen many examples in the net but i am unable to resolve it Pls help me.

Here is my code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.form);
    Seen = (ImageView) findViewById(R.id.SeenStatus);       


    new GetDescendingDate().execute();
    userArray = new ArrayList<listmodel>();

    ListView lv = getListView();


    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String Id = ((TextView) view.findViewById(R.id.txtId))
                    .getText().toString();

            // Starting single activity
            Intent in = new Intent(getApplicationContext(),
                    details.class);
            in.putExtra("TAG_Id", Id);
            startActivity(in);


    });



    }

}


private class GetDescendingDate extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(Atab.this);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    protected Void doInBackground(Void... arg0) {

        JSONParser jParser = new JSONParser();

        // Getting JSON Array node
        JSONArray json;

        session = new SessionManager(getApplicationContext());
        session.checkLogin();
        HashMap<String, String> user = session.getUserDetails();
        String email = user.get(SessionManager.KEY_EMAIL);
        String Status = "New";
        String get;
        get = URL.Get;
        String url_new = get + email + "/" + Status + "/" + "SODD"
                + "/" + "null" + "/" + "0" + "/" + "10";
        try {
            json = jParser.getJSONFromUrl(url_new);

            if (json != null) {
                // looping through All Orders
                for (int i = 0; i < json.length(); i++) {
                    try {
                        JSONObject c = json.getJSONObject(i);

                        String number = c.getString("No");
                        String By = c.getString("By");
                        String Type = c.getString("Type");
                        String Descripton = c.getString("Desc");
                        String Date = c.getString("DateTime");
                        String Id = c.getString("Id");
                        String ONo = c.getString("ONo");
                        String FirstName = c        .getString("FirstName");
                        String Price = c.getString("Price");


                        listmodel list = new listmodel();
                        list.setId(Id);
                        list.setBy(By);
                        list.setType(Type);
                        list.setDescription(Descripton);
                        list.setDate(Date);
                        list.setPrice(Price);
                        list.setName(FirstName);

                        userArray.add(list);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            else {
                Log.e("New", "Couldn't get any data from the url");

            }
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        if (pDialog.isShowing())
            pDialog.dismiss();

        adapter = new adapter(Atab.this,userArray);         
        setListAdapter(adapter);


    }

}

标签: android
3条回答
冷血范
2楼-- · 2020-03-03 09:51

You can implement like this..

 listView.setOnScrollListener(new OnScrollListener() {
        private int currentVisibleItemCount;
        private int currentScrollState;
        private int currentFirstVisibleItem;
        private int totalItem;
        private LinearLayout lBelow;


        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub
            this.currentScrollState = scrollState;
            this.isScrollCompleted();               
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
            this.currentFirstVisibleItem = firstVisibleItem;
            this.currentVisibleItemCount = visibleItemCount;
            this.totalItem = totalItemCount;


        }

        private void isScrollCompleted() {
            if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
                    && this.currentScrollState == SCROLL_STATE_IDLE) {
             /** To do code here*/


        }
    });
查看更多
混吃等死
3楼-- · 2020-03-03 10:01

The easiest option

First you need to add the list footer and assign OnScrollListener

ProgressBar footer = new ProgressBar(this);
listView.addFooterView(footer);
listView.setOnScrollListener(scrollListener);

and this realization OnScrollListener

private AbsListView.OnScrollListener scrollListener = new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            int lastInScreen = firstVisibleItem + visibleItemCount;
            if(lastInScreen == totalItemCount && !isLoading){
                loadMoreItems(totalItemCount - 1);
                isLoading = true;
            }
        }
    };

server gave me the records of 10 elements

isLoading changes when the download is complete

totalItemCount - 1 start position(footer is also an element of the list)

after completion you need to add new elements to the adapter adapter.addAll(list); and cause adapter.notifyDataSetChanged (); and put isLoading = false;

查看更多
家丑人穷心不美
4楼-- · 2020-03-03 10:10

It is following:

public OnScrollListener scrollListener = new OnScrollListener() 
{
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) 
    { 
         if((firstVisibleItem + visibleItemCount) >= totalItemCount) && /*also maybe some condition else*/) 
         {    

             //here start next 10 items request                   
         }


    @Override
    public void onScrollStateChanged(AbsListView arg0, int arg1) {
            // TODO Auto-generated method stub

    }

};

If your server gives the next 10 items request URL like nextUrl in each repose, then you could check if nextUrl is null or not in the condition else, if null means no more items available.

Finally remeber set listener to your ListView:

yourListView.setOnScrollListener(scrollListener);
查看更多
登录 后发表回答