Android的使用GridView控件与OnScrollListener [英] Android Using GridView with OnScrollListener

查看:307
本文介绍了Android的使用GridView控件与OnScrollListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立包含图像可能围绕10​​00 ++的图片很多一个gridview。为了减少加载时间为GridView,我想实现使用AbsListView的onScrollListener。我将限制20个图像按次,那么当滚动到达底部,将加载另一个20幅图像。这将重复进行,直到所有的图像已经加载。

我一直在使用Google的样品,但似乎没有找到一个适合我的codeS。任何人都可以请指导我,这是怎么做的?我目前使用ImageLoader的Lazylist为我的图片。另外我使用的AsyncTask。

MainGridView.class

 公共类MainGridView扩展SherlockActivity {

    私人ProgressDialog pDialog;
    ArrayList的< HashMap的<字符串,字符串>> songsList;
    静态最后弦乐KEY_SONG =歌;
    静态最后弦乐KEY_ID =ID;
    静态最后弦乐KEY_TITLE =称号;
    静态最后弦乐KEY_ARTIST =艺术家;
    静态最后弦乐KEY_CAT_ARTIST =artistcat;
    静态最后弦乐KEY_DURATION =持续时间;
    静态最后弦乐KEY_THUMB_URL =thumb_url;
    静态最后弦乐KEY_BIG_URL =big_url;
    静态最后弦乐KEY_CAT_URL =cat_url;
    静态字符串IMAGE_POSITION;
    GridView的网格;
    MainGridViewLazyAdapter适配器;
    字符串cat_url;
    字符串artist_url;
    私人诠释visibleThreshold = 5;
    私人诠释当前页= 0;
    私人诠释previousTotal = 0;
    私人布尔负荷=真;
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.gridview_main);

        getSupportActionBar()setDisplayHomeAsUpEnabled(真)。
        checkInternetConnection();

        格=(GridView控件)findViewById(R.id.grid_view);




    grid.setOnScrollListener(新OnScrollListener(){

    @覆盖
    公共无效onScroll(AbsListView观点,诠释firstVisibleItem,
            INT visibleItemCount,诠释totalItemCount){
        // TODO自动生成方法存根
        如果(装载){
            如果(visibleItemCount> totalItemCount){
                装载= FALSE;
                previousTotal = totalItemCount;
                当前是++;
            }
        }
        如果(装载和放大器;&安培;!(totalItemCount  -  visibleItemCount)< =(firstVisibleItem + visibleThreshold)){
            //我加载使用一个后台任务演出的下一个页面,
            //但你可以在这里调用任何功能。
            新loadGridView()执行(当前页+ 1);
            加载=真正的;
        }
    }

    @覆盖
    公共无效onScrollStateChanged(AbsListView观点,诠释scrollState){
        // TODO自动生成方法存根

    }
    });


}

    公共类loadGridView扩展的AsyncTask<整数,字符串,字符串> {

        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            pDialog =新ProgressDialog(MainGridView.this);
            pDialog.setTitle(连接到服务器);
            pDialog.setMessage(这个过程可能需要几秒钟到几分钟,这取决于你的互联网连接速度。);
            pDialog.setIndeterminate(假);
            pDialog.setCancelable(假);
            pDialog.show();
        }
        @覆盖
        保护字符串doInBackground(整数参数... args){
            //从后台线程更新UI
                    意图= getIntent();
                    songsList =新的ArrayList< HashMap的<字符串,字符串>>();
                    cat_url = in.getStringExtra(KEY_CAT_URL);
                    artist_url = in.getStringExtra(KEY_CAT_ARTIST);


                    XMLParser的分析器=新XMLParser的();
                    XML字符串= parser.getXmlFromUrl(cat_url); //获取XML的URL
                    文档DOC = parser.getDomElement(XML); //获取DOM元素

                    NodeList的NL = doc.getElementsByTagName(KEY_SONG);
                    //遍历所有歌曲节点<宋>
                    的for(int i = 0; I< nl.getLength();我++){
                        //创建新的HashMap
                        HashMap的<字符串,字符串>图=新的HashMap<字符串,字符串>();
                        元素e =(元)nl.item(我);
                        //添加每个子节点HashMap中的key =>值
                        map.put(KEY_ID,parser.getValue(即KEY_ID));
                        map.put(KEY_TITLE,parser.getValue(即KEY_TITLE));
                        map.put(KEY_ARTIST,parser.getValue(即KEY_ARTIST));
                        map.put(KEY_DURATION,parser.getValue(即KEY_DURATION));
                        map.put(KEY_THUMB_URL,parser.getValue(即KEY_THUMB_URL));
                        map.put(KEY_BIG_URL,parser.getValue(即KEY_BIG_URL));
                        //添加HashList到ArrayList中
                        songsList.add(图)

                    }
                    返回null;
                }


        @覆盖
        保护无效onPostExecute(字符串参数){
            动作条AB = getSupportActionBar();
                        ab.setTitle(artist_url);

            适配器=新MainGridViewLazyAdapter(MainGridView.this,songsList);
            grid.setAdapter(适配器);
            pDialog.dismiss();
            }
        }
 

解决方案

我想你想从URL中加载图像。为了这个目的,你可以使用此解决方案:<一href="http://stackoverflow.com/questions/541966/android-how-do-i-do-a-lazy-load-of-images-in-listview/3068012#3068012">Android - 如何做我做的ListView图像的延迟加载

为了使用 onScrollListener 来控制你的传呼,我想你想看到的无限滚动的例子。这是一个简单的例子,但你必须添加的唯一的事情是检查,如果你已经达到你的XML的最后一个项目。

在你的的AsyncTask (被称为在每个新的加载),你只分析了一下,从您的XML数据(相当于20个项目在你的情况)。这是使用基于你的code的例子:

 公共类MainGridView扩展SherlockActivity实现OnScrollListener {

    公共静态最后弦乐KEY_SONG =歌;
    公共静态最后弦乐KEY_ID =ID;
    公共静态最后弦乐KEY_TITLE =称号;
    公共静态最后弦乐KEY_ARTIST =艺术家;
    公共静态最后弦乐KEY_CAT_ARTIST =artistcat;
    公共静态最后弦乐KEY_DURATION =持续时间;
    公共静态最后弦乐KEY_THUMB_URL =thumb_url;
    公共静态最后弦乐KEY_BIG_URL =big_url;
    公共静态最后弦乐KEY_CAT_URL =cat_url;

    私人最终静态INT ITEMS_PPAGE = 20;

    私人ProgressDialog mDialog;
    私人的ArrayList&LT; HashMap的&LT;字符串,字符串&GT;&GT; mSongsList;

    私有静态字符串IMAGE_POSITION;
    私人的GridView mGridView;
    // MainGridViewLazyAdapter mAdapter;
    私人ArrayAdapter&LT;字符串&GT; mAdapter;
    私人字符串cat_url;
    私人字符串artist_url;

    私人诠释mVisibleThreshold = 5;
    私人诠释mCurrentPage = 0;
    私人诠释米previousTotal = 0;
    私人布尔mLoading = TRUE;
    私人布尔mLastPage = FALSE;

    私人字符串MXML;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        setTheme(SherlockBarUtils.getCurrentTheme(本));
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.gridview_main);

        getSupportActionBar()setDisplayHomeAsUpEnabled(真)。
        // checkInternetConnection();

        mGridView =(GridView控件)findViewById(R.id.grid_view);
        mGridView.setOnScrollListener(本);

        mAdapter =新的ArrayAdapter&LT;字符串&GT;(这一点,android.R.layout.simple_list_item_1);
        // mAdapter =新MainGridViewLazyAdapter(MainGridView.this);
        mGridView.setAdapter(mAdapter);

        新DownloadDataAsyncTask()执行()。
    }

    @覆盖
    公共无效onScroll(AbsListView观点,诠释firstVisibleItem,诠释visibleItemCount,诠释totalItemCount){

        如果(mLoading){
            如果(totalItemCount&GT,M previousTotal){

                mLoading = FALSE;
                米previousTotal = totalItemCount;
                mCurrentPage ++;

                //找到自己的状态,以便知道,当你
                //已完成显示的所有项目
                如果(mCurrentPage + 1→50){
                    mLastPage =真;
                }
            }
        }
        如果(mLastPage&安培;!&安培;!mLoading和放大器;&安培;
                (totalItemCount  -  visibleItemCount)其中=(firstVisibleItem + mVisibleThreshold)){
            新AddItemsAsyncTask()执行();
            mLoading =真;
        }
    }

    @覆盖
    公共无效onScrollStateChanged(AbsListView观点,诠释scrollState){

    }

    公共类DownloadDataAsyncTask扩展的AsyncTask&LT;字符串,字符串,字符串&GT; {

        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            mDialog =新ProgressDialog(MainGridView.this);
            mDialog.setTitle(连接到服务器);
            mDialog.setMessage(这个过程可能需要几秒钟到几分钟,这取决于你的互联网连接速度。);
            mDialog.setIndeterminate(假);
            mDialog.setCancelable(假);
            mDialog.show();
        }
        @覆盖
        保护字符串doInBackground(字符串参数... args){

            //下载XML

            / *
            意图= getIntent();
            mSongsList =新的ArrayList&LT; HashMap的&LT;字符串,字符串&GT;&GT;();
            cat_url = in.getStringExtra(KEY_CAT_URL);
            artist_url = in.getStringExtra(KEY_CAT_ARTIST);

            XMLParser的分析器=新XMLParser的();
            MXML = parser.getXmlFromUrl(cat_url); //获取XML的URL
            * /

            返回null;
        }

        @覆盖
        保护无效onPostExecute(字符串参数){

            / *
            getSupportActionBar()的setTitle(artist_url)。
            * /
            mDialog.dismiss();
            mLoading = FALSE;
        }
    }

    公共类AddItemsAsyncTask扩展的AsyncTask&LT;整数,字符串,字符串&GT; {

        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
        }
        @覆盖
        保护字符串doInBackground(整数参数... args){

            MainGridView.this.runOnUiThread(新的Runnable(){

                @覆盖
                公共无效的run(){

                    //解析20更多的项目,并把它们添加到适配器
                    的for(int i = mCurrentPage * ITEMS_PPAGE; I&LT;(mCurrentPage + 1)* ITEMS_PPAGE;我++){
                        MainGridView.this.mAdapter.add(将String.valueOf(的Math.random()* 5000));
                    }
                    MainGridView.this.mAdapter.notifyDataSetChanged();
                }
            });
            返回null;
        }

        @覆盖
        保护无效onPostExecute(字符串参数){

        }
    }
}
 

为了方便,我用来代替的GridView 里面的图像文本。我专注于寻呼系统,所以我没有解析XML的,只是增加了对飞一些随机值。

此外,您可以考虑使用相同的 addItemsAsyncTask 只下载在创建之前下载整个1000多个项目的XML在每个装载的一部分(20个项目),而不是在的GridView

I'm building a gridview that contains alot of images likely around 1000++ pictures. To reduce the loading time for the gridview, I want to implement an onScrollListener using AbsListView. I will limit 20 images per view, then when scrolling reaches bottom it will load another 20 images. This will repeat until all images has been loaded.

I've been googling samples, but doesnt seem to find one that suits my codes. Could anyone please guide me how it is done? I'm currently using imageloader Lazylist for my images. Also I'm using AsyncTask.

MainGridView.class

    public class MainGridView extends SherlockActivity {

    private ProgressDialog pDialog;
    ArrayList<HashMap<String, String>> songsList;
    static final String KEY_SONG = "song"; 
    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_ARTIST = "artist";
    static final String KEY_CAT_ARTIST = "artistcat";
    static final String KEY_DURATION = "duration";
    static final String KEY_THUMB_URL = "thumb_url";
    static final String KEY_BIG_URL = "big_url";
    static final String KEY_CAT_URL = "cat_url";
    static String IMAGE_POSITION;
    GridView grid;
    MainGridViewLazyAdapter adapter;
    String cat_url;
    String artist_url;
    private int visibleThreshold = 5;
    private int currentPage = 0;
    private int previousTotal = 0;
    private boolean loading = true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridview_main);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        checkInternetConnection();

        grid = (GridView) findViewById(R.id.grid_view);




    grid.setOnScrollListener(new OnScrollListener() {

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        // TODO Auto-generated method stub
        if (loading) {
            if (visibleItemCount > totalItemCount) {
                loading = false;
                previousTotal = totalItemCount;
                currentPage++;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
            // I load the next page of gigs using a background task,
            // but you can call any function here.
            new loadGridView().execute(currentPage + 1);
            loading = true;
        }
    }

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

    }
    });


}

    public class loadGridView extends AsyncTask<Integer, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainGridView.this);
            pDialog.setTitle("Connect to Server");
            pDialog.setMessage("This process can take a few seconds to a few minutes, depending on your Internet Connection Speed.");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
        @Override
        protected String doInBackground(Integer... args) {
            // updating UI from Background Thread
                    Intent in = getIntent();
                    songsList = new ArrayList<HashMap<String, String>>();
                    cat_url = in.getStringExtra(KEY_CAT_URL);
                    artist_url = in.getStringExtra(KEY_CAT_ARTIST);


                    XMLParser parser = new XMLParser();
                    String xml = parser.getXmlFromUrl(cat_url); // getting XML from URL
                    Document doc = parser.getDomElement(xml); // getting DOM element

                    NodeList nl = doc.getElementsByTagName(KEY_SONG);
                    // looping through all song nodes <song>
                    for (int i = 0; i < nl.getLength(); i++) {
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        Element e = (Element) nl.item(i);
                        // adding each child node to HashMap key => value
                        map.put(KEY_ID, parser.getValue(e, KEY_ID));
                        map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
                        map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
                        map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
                        map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
                        map.put(KEY_BIG_URL, parser.getValue(e, KEY_BIG_URL));
                        // adding HashList to ArrayList
                        songsList.add(map);

                    }
                    return null;
                }   


        @Override
        protected void onPostExecute(String args) {
            ActionBar   ab = getSupportActionBar();
                        ab.setTitle(artist_url);

            adapter=new MainGridViewLazyAdapter(MainGridView.this, songsList);   
            grid.setAdapter(adapter);
            pDialog.dismiss();
            }
        }

解决方案

I suppose you want to load images from Urls. For that purpose, you could use this solution: Android - How do I do a lazy load of images in ListView

In order to control your paging using onScrollListener, I think you want to see the Endless scrolling example. This is a simplistic example, but the only thing you have to add is a check if you have reached the last item of your xml.

Inside your AsyncTask (called at each new loading), you would only parse a bit of data from your xml (corresponding to 20 items in your case). This is an example of use based on your code:

public class MainGridView extends SherlockActivity implements OnScrollListener {

    public static final String KEY_SONG = "song"; 
    public static final String KEY_ID = "id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_ARTIST = "artist";
    public static final String KEY_CAT_ARTIST = "artistcat";
    public static final String KEY_DURATION = "duration";
    public static final String KEY_THUMB_URL = "thumb_url";
    public static final String KEY_BIG_URL = "big_url";
    public static final String KEY_CAT_URL = "cat_url";

    private final static int ITEMS_PPAGE = 20;

    private ProgressDialog mDialog;
    private ArrayList<HashMap<String, String>> mSongsList;

    private static String IMAGE_POSITION;
    private GridView mGridView;
    //MainGridViewLazyAdapter mAdapter;
    private ArrayAdapter<String> mAdapter;
    private String cat_url;
    private String artist_url;

    private int mVisibleThreshold = 5;
    private int mCurrentPage = 0;
    private int mPreviousTotal = 0;
    private boolean mLoading = true;
    private boolean mLastPage = false;

    private String mXml;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setTheme(SherlockBarUtils.getCurrentTheme(this));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridview_main);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //checkInternetConnection();

        mGridView = (GridView) findViewById(R.id.grid_view);
        mGridView.setOnScrollListener(this);

        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        //mAdapter=new MainGridViewLazyAdapter(MainGridView.this);  
        mGridView.setAdapter(mAdapter);

        new DownloadDataAsyncTask().execute();
    }

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

        if (mLoading) {
            if (totalItemCount > mPreviousTotal) {

                mLoading = false;
                mPreviousTotal = totalItemCount;
                mCurrentPage++;

                // Find your own condition in order to know when you 
                // have finished displaying all items
                if (mCurrentPage + 1 > 50) {
                    mLastPage = true;
                }
            }
        }
        if (!mLastPage && !mLoading && 
                (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) {
            new AddItemsAsyncTask().execute();
            mLoading = true;
        }
    }

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

    }

    public class DownloadDataAsyncTask extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mDialog = new ProgressDialog(MainGridView.this);
            mDialog.setTitle("Connect to Server");
            mDialog.setMessage("This process can take a few seconds to a few minutes, depending on your Internet Connection Speed.");
            mDialog.setIndeterminate(false);
            mDialog.setCancelable(false);
            mDialog.show();
        }
        @Override
        protected String doInBackground(String... args) {

            // Downloading XML

            /*
            Intent in = getIntent();
            mSongsList = new ArrayList<HashMap<String, String>>();
            cat_url = in.getStringExtra(KEY_CAT_URL);
            artist_url = in.getStringExtra(KEY_CAT_ARTIST);

            XMLParser parser = new XMLParser();
            mXml = parser.getXmlFromUrl(cat_url); // getting XML from URL
            */

            return null;
        }   

        @Override
        protected void onPostExecute(String args) {

            /*
            getSupportActionBar().setTitle(artist_url);
            */
            mDialog.dismiss();
            mLoading = false;
        }
    }

    public class AddItemsAsyncTask extends AsyncTask<Integer, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(Integer... args) {

            MainGridView.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {

                    // Parsing 20 more items and adding them to the adapter
                    for (int i = mCurrentPage * ITEMS_PPAGE; i < (mCurrentPage + 1) * ITEMS_PPAGE; i++) {
                        MainGridView.this.mAdapter.add(String.valueOf(Math.random() * 5000));
                    }
                    MainGridView.this.mAdapter.notifyDataSetChanged();
                }
            });
            return null;
        }

        @Override
        protected void onPostExecute(String args) {

        }
    }
}

For the convenience, I used texts instead of images inside the GridView. I focused on the paging system so I didn't parse XML, just added some random values on the fly.

Also, you could consider using the same addItemsAsyncTask to download only a part (20 items) of your xml at each loading instead of downloading the whole 1000+ items before creating the GridView.

这篇关于Android的使用GridView控件与OnScrollListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆