在滚动结束时将更多项目附加到 listfragment

Posted

技术标签:

【中文标题】在滚动结束时将更多项目附加到 listfragment【英文标题】:append more items to listfragment on scroll end 【发布时间】:2014-03-14 20:54:40 【问题描述】:

我知道在 *** 上有很多关于这个问题的例子,但我不知道如何在我的代码中实现它们中的任何一个。

我想要做的是从 json url 加载数据(前 15 个元素),并将它们附加到 listfragment 并且当用户向下滚动到列表末尾时附加另外 15 个元素(列表中总共 30 个元素)等等..

现在我可以正确获取前 15 个元素,但是当我尝试在用户到达滚动末尾时添加更多项目时,我不知道该怎么做......这是我的代码:

MainActivity 我有以下扩展 listfragment 的类:

  public static class NewsFragment extends ListFragment implements ILoadDataListener, OnScrollListener 

         private ListView listView; 
         private NewsAdapter newsAdapter;
         private  int currentPage=1;
         @Override
         public  View  onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceStatee)

             View rootView = inflater.inflate(R.layout.fragment_news, container, false);
             listView = (ListView) rootView.findViewById(android.R.id.list);
             return rootView;
         

         @Override
          public void onActivityCreated(Bundle savedInstanceState) 
            super.onActivityCreated(savedInstanceState);
            getListView().setOnScrollListener( this);
            // URL to the JSON data         
            String strUrl = "http://opetmar.hostzi.com/test.php";
         // Creating a new non-ui thread task to download json data 
            ProgressDialog progress = new ProgressDialog(getActivity());
            progress.setMessage("loading ...");
            GetJSON downloadTask = new GetJSON(this , progress , "news");

            // Starting the download process
            downloadTask.execute(strUrl);       


          


         @Override
            public void onComplete(String[] titles  , String[] images , String[] ids , String[] snippets , String[] data) 
            if ( currentPage == 1 )
                newsAdapter = new NewsAdapter( getActivity() , titles , images , ids , snippets , data );
                listView.setAdapter(newsAdapter); 
            else 

            
            

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

                super.onListItemClick(l, v, position, id);
                DataHolder holder;
                holder  = (DataHolder) v.getTag();
                Intent myIntent = new Intent(getActivity(), NewsOpen.class);
                myIntent.putExtra("image", holder.image);
                myIntent.putExtra("data", holder.data); 
                startActivity(myIntent);
            

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

         

         @Override
         public void onScrollStateChanged(AbsListView listView, int scrollState) 
             if (scrollState == SCROLL_STATE_IDLE) 
                    if (listView.getLastVisiblePosition() >= listView.getCount() - 1 ) 
                        currentPage++;  
                        String strUrl = "http://opetmar.hostzi.com/test.php?page="+currentPage;
                            ProgressDialog progress = new ProgressDialog(getActivity());
                            progress.setMessage("loading ...");
                            GetJSON downloadTask = new GetJSON(this , progress , "news");

                            // Starting the download process
                            downloadTask.execute(strUrl);       
                    
                


         
    

NewsAdapter.java

public class NewsAdapter extends ArrayAdapter<String> 

private final Context context;
private final String[] titles;
private final String[] images;
private final String[] ids;
private final String[] snippets;
private final String[] data;
public NewsAdapter(Context context, String[] titles, String[] images , String[] ids , String[] snippets , String[] data) 
    super(context, R.layout.drawer_list_item, titles);
    this.context = context;
    this.titles = titles;
    this.images = images;
    this.ids = ids;
    this.snippets = snippets;
    this.data = data;


@Override
public View getView(int position, View convertView, ViewGroup parent) 
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.news_list_item, parent, false);
    TextView title = (TextView) rowView.findViewById(R.id.news_title);
    TextView snippet = (TextView) rowView.findViewById(R.id.news_snippet);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.news_thumble);
    title.setText(titles[position]);
    snippet.setText(snippets[position]);
    DataHolder holder = new DataHolder();
    holder.data=data[position];
    holder.image=images[position];
    rowView.setTag(holder);
    new DownloadImageTask(imageView).execute(images[position]);

    return rowView;



   public class DataHolder 
   String image;
   String data;

 

   

GetJSON.java

   /** AsyncTask to download json data */
    public class GetJSON extends AsyncTask<String, Integer, String>
    String data = null;
    private ListView listView;  
 private NewsAdapter newsAdapter;
 private ILoadDataListener mListener;
private ProgressDialog progress;
private String type;

   public GetJSON(ILoadDataListener listener ,  ProgressDialog progress , String type) 
       this.mListener = listener;
       this.progress = progress;
       this.type = type;
   
   public void onPreExecute() 
        progress.show();
      

        @Override
        protected String doInBackground(String... url) 
                try
                    data = downloadUrl(url[0]);

                catch(Exception e)
                    Log.d("Background Task",e.toString());
                
                return data;
        

        @Override
        protected void onPostExecute(String result) 
            if (result != null)
         if (this.type == "news") 
            try 
                JSONObject jObject;
                jObject = new JSONObject(result);
                JSONArray jCountries = jObject.optJSONArray("news");
                ArrayList<String> stringArrayList = new ArrayList<String>();
                ArrayList<String> stringArrayList2 = new ArrayList<String>();
                ArrayList<String> stringArrayList3 = new ArrayList<String>();
                ArrayList<String> stringArrayList4 = new ArrayList<String>();
                ArrayList<String> stringArrayList5 = new ArrayList<String>();
                for (int i=0; i < jCountries.length(); i++)
                
                    try 
                        JSONObject oneObject = jCountries.getJSONObject(i);
                        // Pulling items from the array
                        stringArrayList.add(oneObject.getString("title"));
                        stringArrayList2.add( oneObject.getString("image"));
                        stringArrayList3.add( oneObject.getString("id"));
                        stringArrayList4.add( oneObject.getString("snippet"));
                        stringArrayList5.add( oneObject.getString("data"));

                     catch (JSONException e) 
                        // Oops
                    
                
                String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);
                String [] stringArray2 = stringArrayList2.toArray(new String[stringArrayList2.size()]);
                String [] stringArray3 = stringArrayList3.toArray(new String[stringArrayList3.size()]);
                String [] stringArray4 = stringArrayList4.toArray(new String[stringArrayList4.size()]);
                String [] stringArray5 = stringArrayList5.toArray(new String[stringArrayList5.size()]);
                progress.dismiss();
                 if (mListener != null)   
                       mListener.onComplete(stringArray , stringArray2 , stringArray3 , stringArray4 , stringArray5);
                   
             catch (JSONException e) 
                e.printStackTrace();
            

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

        /** A method to download json data from url */
        private String downloadUrl(String strUrl) throws IOException
            String data = "";
            InputStream iStream = null;
            try
                    URL url = new URL(strUrl);

                    // Creating an http connection to communicate with url 
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                    // Connecting to url 
                    urlConnection.connect();

                    // Reading data from url 
                    iStream = urlConnection.getInputStream();

                    BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                    StringBuffer sb  = new StringBuffer();

                    String line = "";
                    while( ( line = br.readLine())  != null)
                        sb.append(line);
                    

                    data = sb.toString();

                    br.close();

            catch(Exception e)
                    Log.d("Exception while downloading url", e.toString());
            finally
                    iStream.close();
            
            return data;

        

   

更具体地说,当用户到达滚动结束时,将触发以下代码,从 json url 加载更多数据:

     @Override
         public void onScrollStateChanged(AbsListView listView, int scrollState) 
             if (scrollState == SCROLL_STATE_IDLE) 
                    if (listView.getLastVisiblePosition() >= listView.getCount() - 1 ) 
                        currentPage++;  
                        String strUrl = "http://opetmar.hostzi.com/test.php?page="+currentPage;
                            ProgressDialog progress = new ProgressDialog(getActivity());
                            progress.setMessage("loading ...");
                            GetJSON downloadTask = new GetJSON(this , progress , "news");

                            // Starting the download process
                            downloadTask.execute(strUrl);       
                    
                

那么GetJSON会在完成获取和解析数据后调用如下方法:

 @Override
            public void onComplete(String[] titles  , String[] images , String[] ids , String[] snippets , String[] data) 
            if ( currentPage == 1 )
                newsAdapter = new NewsAdapter( getActivity() , titles , images , ids , snippets , data );
                listView.setAdapter(newsAdapter); 
            else 

            
            

所以如果 currentpage 不等于一,我想追加更多数据。如何做到这一点?

【问题讨论】:

【参考方案1】:

我不确定 ListView 是否可以,但使用 Gallery 你可以覆盖

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);

并使用它来定义项目滚动到末尾时的事件。我这样做是为了在图库中组织无限的日历 ietms 列表。

问候,

亚历克斯。

【讨论】:

以上是关于在滚动结束时将更多项目附加到 listfragment的主要内容,如果未能解决你的问题,请参考以下文章

UICollectionView 在滚动 Alamofire 时将图像加载到错误的位置

Flutter/Firestore:如何在滚动时将项目添加到流中(完成获取时保留滚动位置)?

Android sqlite数据库-如何在滚动结束时显示列表视图添加 "加载更多项目"。

Swift,将更多数据加载到表视图中会导致滚动滞后

滚动时将功能分配给 UIScrollView (Swift)

滚动时将新项目添加到列表时出现数组索引超出范围异常