1

Я знаю, что есть много примеров для этого вопроса в stackoverflow, но я не знаю, как реализовать любой из них в моем коде.добавить больше элементов в listfragment на конец прокрутки

Что я хочу сделать, это загрузить данные из 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 не равно один, я хочу, чтобы добавить больше данных. как добиться этого?

ответ

0

Я не уверен, можно ли для ListView, но с помощью галереи вы можете переопределить

общественного логический onFling (MotionEvent e1, e2 MotionEvent, плавать velocityX, плавать velocityY);

и использовать его для определения событий, когда элементы прокручиваются до конца. Я сделал это, чтобы организовать бесконечный список календарей ietms в галерее.

С уважением,

Alex.

 Смежные вопросы

  • Нет связанных вопросов^_^