开发者

Gridview pagination in android

开发者 https://www.devze.com 2023-02-17 04:45 出处:网络
i retrieved texts+images from DB and displayed it in a gridview.i.e.each gridview cell c开发者_Go百科onsists of one image+one text.Now i\'ve to do pagination for that.i\'ve to allow it to display 4 ce

i retrieved texts+images from DB and displayed it in a gridview.i.e.each gridview cell c开发者_Go百科onsists of one image+one text.Now i've to do pagination for that.i've to allow it to display 4 cells per page.How could i do that?Example link or code is much appreciated.


//try this one---

gridView.setOnScrollListener(new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {

        }

        @Override
        public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (totalItemCount > 0) {
                int lastVisibleItem = firstVisibleItem + visibleItemCount;
                if (!isLoading && hasMoreItems && (lastVisibleItem == totalItemCount)) {
                    isLoading = true;
                    //load more items--

                }
            }
        }
    });


I hope this helps..

I found an example on the Android Training page link "http://developer.android.com/training/implementing-navigation/index.html" there you can download an example EffectiveNavigation.zip, is very usefull for pagers. From there you will get the basics of the adapters and stuff you need for this.

the way I achieved a grid with pagination is:

having 2 layouts 1 with the pager

<android.support.v4.view.ViewPager ...

and one for the grid view

<GridView  android:id="@+id/gridview" ... 

Note: the grid layout if is wraped in other component I was having issues.

I load the pager within an Activity, here you load the paginator as the android training example I dont add the information here seance is well explained in there. here as well I've my logic to load the array of items in this case you load them from json response I make a AsyncTask once is complete on the:

protected void onPostExecute(String params) {
    refresList();
    progressDialog.dismiss();
}

I call the refreshItems method that this will notyfy the pager adapter that something has changed "mGridPagerAdapter.notifyDataSetChanged();" as well I call a refresh tabs method to recauculate the tabs to be showed.

public void refrestTabs() {
    actionBar.removeAllTabs();
    for (int i = 0; i < mGridPagerAdapter.getCount(); i++) {
        actionBar.addTab(actionBar.newTab()
                .setText(mGridPagerAdapter.getPageTitle(i))
                .setTabListener(this));
    }
}

I've created a GridAdapter that extends FragmentPagerAdapter in here on the getItem method load the Fragment

@Override
public Fragment getItem(int i) {
    Fragment fragment = new GridListFragment();
    Bundle args = new Bundle();
    args.putInt(GridListFragment.ARG_SECTION_NUMBER, i);
    fragment.setArguments(args);
    return fragment;
}

the class GridListFragment extends fragment and here goes your logic to load the section of the array you want. here is onCreateView method that I use

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,   Bundle savedInstanceState) {
    Bundle args = getArguments();
    position =  args.getInt(ARG_SECTION_NUMBER);
    View view = inflater.inflate(R.layout.comp_grid_view, container, false); 
    gridView = (GridView) view.findViewById(R.id.gridview);
    applicationItems = new ArrayList<ApplicationItem>();
    int resID = R.layout.comp_app_list_item;
    aa = new ApplicationListItemAdapter(view.getContext(), resID, applicationItems);
    gridView.setAdapter(aa);
    gridView.setOnItemClickListener(new OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position,
                long id) {
            mCallback.onApplicationSelected(applicationItems.get(position));
        }}
    );
    return view;
}

I refresh the grid when the onStart method is called and I do it this way:

@Override
public void onStart() {
    applicationItems.clear();   
    AppShortcutApplication appState = ((AppShortcutApplication)getActivity().getApplicationContext());
    List<ApplicationItem> l = appState.getCurrentListApplications();
    if (l != null){
        applicationItems.clear();
        applicationItems.addAll(l);
        aa.notifyDataSetChanged();      
    }
    super.onStart();
}

I pass the items thru the application state you can find information about that on this other question link "How do I pass data between Activities in Android application?"

Again this may not be the best approach but coultn't find anything else.


This is what iam doing in one of my apps. Hope it helps.

public static int currentPage = 0;
private boolean endOfAlbums = false;
private int lastItem = 0;

albumGrid.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                    // Pause fetcher to ensure smoother scrolling when flinging // You can ignore this part
                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
                        mImageFetcher.setPauseWork(true);
                    } else {
                        mImageFetcher.setPauseWork(false);
                    }
                }

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

                    final int _lastItem = firstVisibleItem + visibleItemCount;
                    if (_lastItem > 0 && totalItemCount > 0)
                        if (_lastItem == albums.size() && !endOfAlbums && lastItem != _lastItem) {
                            lastItem = _lastItem;
                            // Last item is fully visible.
                            loadAlbums();
                        }
                }
            });

            return view;
        }

        private void loadAlbums() {

            if (currentPage == 0) {
                albums.clear();
                endOfAlbums = false;
                lastItem = 0;
                // get new releases
                progressLayout.setVisibility(View.VISIBLE);
            } else
                progressLoadMore.setVisibility(View.VISIBLE);

            if (Utility.isNetworkAvailable(getActivity())) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        // get the serverAlbums
                        ArrayList<Album> serverAlbums = ServerAPI.getAllAlbums(session.getLanguage(), currentPage);
                        if (serverAlbums.size() > 0)
                            albums.addAll(serverAlbums);
                        else
                            endOfAlbums = true;

                        currentPage++;

                        myHandler.post(updateRunnable);
                    }
                }).start();
                updateRunnable = new Runnable() {
                    @Override
                    public void run() {

                        if (albums.size() > 0) {

                            imageAdapter.notifyDataSetChanged();
                            // get listview current position - used to maintain scroll position
                            int currentPosition = albumGrid.getFirstVisiblePosition();

                            // Setting new scroll position
                            albumGrid.smoothScrollToPosition(currentPosition + 1, 0);
                        } else
                            tvNoAlbums.setVisibility(View.VISIBLE);

                        progressLayout.setVisibility(View.GONE);
                        progressLoadMore.setVisibility(View.GONE);
                    }
                };
            } else {
                Toast.makeText(getActivity(), R.string.check_connectivity, Toast.LENGTH_SHORT).show();
                progressLayout.setVisibility(View.GONE);
                progressLoadMore.setVisibility(View.GONE);
            }

        }


I think this might help you. It covers the basics behind displaying multiple items on a GridView with code examples.

Android GridView Develop Guide

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号