web-dev-qa-db-fra.com

Comment implémenter la pagination dans Android listview

Je travaille pour Android, dans laquelle je dois afficher listview avec des éléments. Mais il y a plus d'éléments à afficher dans listview.

J'ai décidé de mettre en œuvre la pagination. J'ai essayé de rechercher dans Google mais je ne trouve aucune information connexe.

Est-ce que quelqu'un peut m'aider s'il vous plaît..

24
Naveen

L'implémentation de la pagination est très simple.

Regardez ça ...

public class MainActivity extends Activity {  

    private ListView listview;
    private TextView title;

   private ArrayList<String> data;
    ArrayAdapter<String> sd;


    public int TOTAL_LIST_ITEMS = 1030;
    public int NUM_ITEMS_PAGE   = 100;
    private int noOfBtns;
    private Button[] btns;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listview = (ListView)findViewById(R.id.list);
        title    = (TextView)findViewById(R.id.title);

        Btnfooter();

        data = new ArrayList<String>();

        /*
         * The ArrayList data contains all the list items
         */
        for(int i=0;i<TOTAL_LIST_ITEMS;i++)
        {
            data.add("This is Item "+(i+1));
        }

        loadList(0);

        CheckBtnBackGroud(0);

    }

    private void Btnfooter()
    {
        int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
        val = val==0?0:1;
        noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;

        LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);

        btns = new Button[noOfBtns];

        for(int i=0;i<noOfBtns;i++)
        {
            btns[i] =   new Button(this);
            btns[i].setBackgroundColor(getResources().getColor(Android.R.color.transparent));
            btns[i].setText(""+(i+1));

            LinearLayout.LayoutParams lp = new     LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            ll.addView(btns[i], lp);

            final int j = i;
            btns[j].setOnClickListener(new OnClickListener() {

                public void onClick(View v)
                {
                    loadList(j);
                    CheckBtnBackGroud(j);
                }
            });
        }

    }

    /**
     * Method for Checking Button Backgrounds
     */
    private void CheckBtnBackGroud(int index)
    {
        title.setText("Page "+(index+1)+" of "+noOfBtns);
        for(int i=0;i<noOfBtns;i++)
        {
            if(i==index)
            {
                btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
                btns[i].setTextColor(getResources().getColor(Android.R.color.white));
            }
            else
            {
                btns[i].setBackgroundColor(getResources().getColor(Android.R.color.transparent));
                btns[i].setTextColor(getResources().getColor(Android.R.color.black));
            }
        }

    }

    /**
     * Method for loading data in listview
     * @param number
     */
    private void loadList(int number)
    {
        ArrayList<String> sort = new ArrayList<String>();

        int start = number * NUM_ITEMS_PAGE;
        for(int i=start;i<(start)+NUM_ITEMS_PAGE;i++)
        {
            if(i<data.size())
            {
                sort.add(data.get(i));
            }
            else
            {
                break;
            }
        }
        sd = new ArrayAdapter<String>(this,
                Android.R.layout.simple_list_item_1,
                sort);
        listview.setAdapter(sd);
    }
}

Fichier XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="fill_parent"
Android:layout_height="fill_parent"
Android:orientation="vertical" >

<TextView
    Android:id="@+id/title"
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content"
    Android:textColor="@Android:color/black"
    Android:gravity="center"
    Android:textSize="16sp"
    Android:background="@Android:color/darker_gray"
    Android:padding="10dp"/>

<ListView
    Android:id="@+id/list"
    Android:divider="#000"
    Android:dividerHeight="1dp"
    Android:cacheColorHint="#00000000"
    Android:layout_width="fill_parent"
    Android:layout_height="0dp"
    Android:layout_weight="1"
    Android:fadingEdge="none"/>

<HorizontalScrollView
    Android:layout_width="fill_parent"
    Android:layout_height="wrap_content">
    <LinearLayout
        Android:id="@+id/btnLay"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:orientation="horizontal" >
    </LinearLayout>
</HorizontalScrollView>
</LinearLayout>

Pour une explication plus claire et le code source, visitez ces liens

Pagination ListView Ex-1

Pagination ListView Ex-2

26
Ram kiran

J'ai créé cette vue de liste personnalisée.

    package com.pixecon.custom.views;

import Android.content.Context;
import Android.util.AttributeSet;
import Android.util.Log;
import Android.view.MotionEvent;
import Android.widget.FrameLayout;
import Android.widget.ListView;

public class PagingListView extends ListView {
    boolean needScroll = true;
    private String TAG = "CustomListView";

    public PagingListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setNeedScroll(boolean needScroll) {
        this.needScroll = needScroll;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        if (!needScroll) {
            return false;
        }
        else {
            return super.onInterceptTouchEvent(event);
        }
    }

    @Override
    public void setOnScrollListener(OnScrollListener l) {
        super.setOnScrollListener(l);
    }

    public void onScrollStarted() {
        //Scroll Started.
    }

    public void onScrollStopped() {
        centralizeTheView();
    }

    private void centralizeTheView() {
        int height = getResources().getDisplayMetrics().heightPixels;
        int centerY = height / 2;

        int visibleFirstItemPosition = getFirstVisiblePosition();
        int visibleLastItemPosition = getLastVisiblePosition();

        Log.d(TAG, "visibleFirstVisible = " + visibleFirstItemPosition);
        Log.d(TAG, "visibleLastVisible = " + visibleLastItemPosition);

        //TODO: Check the calcualted value and reconfirm.
        int firstPositionInGroup = visibleFirstItemPosition % 2 - 1;
        if (firstPositionInGroup < 0) {
            firstPositionInGroup = 0;
        }

        FrameLayout layout = (FrameLayout) getChildAt(firstPositionInGroup);
        int bottom = layout.getBottom();

        //Calculate the exact bottom of the view by subtracting
        if (bottom > centerY) {
            Log.d(TAG, "First Item - " + visibleFirstItemPosition);
            /*listView.smoothScrollBy(3, 1);*/
            //listView.smoothScrollToPosition(visibleFirstItemPosition);
            setSelection(visibleFirstItemPosition);
        }
        else {
            Log.d(TAG, "Last Item - " + visibleLastItemPosition);
            /*listView.smoothScrollBy(-3, 1);*/
            //listView.smoothScrollToPosition(visibleLastItemPosition);
            setSelection(visibleLastItemPosition);
        }
    }

}
2
Hardik4560