ListView onScroll添加更多项目

时间:2015-09-07 19:17:08

标签: java android listview android-listview android-asynctask

    private class getArticles extends AsyncTask<Void, Void, Void> {

    String url;

    getArticles(String paramUrl) {
        this.url = paramUrl;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(App.this);
        mProgressDialog.setMessage("Učitavanje artikala...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {

        arraylist = new ArrayList<>();

        try {

            Document document = Jsoup.connect(url).get();
            Elements els = document.select("ul.category3 > li");

            for (Element el : els) {

                HashMap<String, String> map = new HashMap<>();

                Elements slika = el.select("div.category3-image > a > img");
                Elements naslov = el.select("div.category3-text > a.main-headline");
                Element datum_noformat = el.select("div.category3-text > div.headlines-info > ul.headlines-info > li").first();
                Element datum = datum_noformat.html(datum_noformat.html().replaceAll("Posted ", ""));
                Elements desc = el.select("div.category3-text > p");
                Elements link = el.select("div.category3-text > a.main-headline");
                Element br_kom = el.select("div.category3-text > div.headlines-info > ul.headlines-info > li.comments-icon").first();

                map.put("naslov", naslov.text());
                map.put("datum", datum.text());
                map.put("desc", desc.text());
                map.put("ikona", slika.attr("src"));
                map.put("link", link.attr("abs:href"));
                map.put("brkom", br_kom.text());
                arraylist.add(map);


            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        listview = (ListView) findViewById(R.id.listview);
        adapter = new ArtikliAdapter(App.this, arraylist);
        listview.setAdapter(adapter);
        mProgressDialog.dismiss();
    }

我搜索了很多onlistview滚动的代码,但是我们并不知道如何实现它。问题是,当我调用我的asynctask时,我有一个url param, 比如new getArticles("http://example.com").execute();

我想实现一个onscrolllistener,但它是这样的,我的param通常设置为:http://www.example.com/category/categoryname/,所以第二页就像http://www.example.com/category/categoryname/page/2/,第三页是http://www.example.com/category/categoryname/page/3/等等。每个页面都有7个需要解析的项目。

我如何实现onscrolllistener,因为url param?

提前致谢。

3 个答案:

答案 0 :(得分:1)

这里你想要拳头添加onscrolllistner到listview

      boolean loading_flage = false;

                                    yourlistview.setOnScrollListener(new OnScrollListener() {

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

                                        }

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

                                            final int lastItem = firstVisibleItem
                                                    + visibleItemCount;

                                            if ((lastItem == totalItemCount)
                                                    & loading_flage == false) {

//this to prevent the list to make more than one request in time
                                                loading_flage = true;
    //you can put the index for your next page here
                                                loadMore(int page);

                                            }

                                        }
                                    });

然后在加载页面后加载更多设置加载为false并解析数据将其添加到您已经拥有的数据

                      //notify the adapter
                     adapter.notifyDataSetChanged();
                      loading_flage = false;

答案 1 :(得分:1)

你可以通过在listview上添加scrolllistener来实现并检查条件,如果列表最后一个可见项在ArrayList中是最后一个,然后使用递增的页码调用asynctask并更新listview,意味着在listview上添加视图并在获取结果之后服务器从列表视图中删除加载更多视图,如下所示 - AndroidListViewLoadMoreActivity.java

public class AndroidListViewLoadMoreActivity extends Activity {

 ArrayList<Country> countryList;
 MyCustomAdapter dataAdapter = null;
 int page = 0;
 boolean loadingMore = false;
 View loadMoreView;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  ListView listView = (ListView) findViewById(R.id.listView1);

  loadMoreView = ((LayoutInflater)this
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE))
    .inflate(R.layout.loadmore, null, false);
  listView.addFooterView(loadMoreView);

  //create an ArrayAdaptar from the String Array
  countryList = new ArrayList<Country>();
  dataAdapter = new MyCustomAdapter(this,
    R.layout.country_info, countryList);
  listView.setAdapter(dataAdapter);

  //enables filtering for the contents of the given ListView
  listView.setTextFilterEnabled(true);

  listView.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    // When clicked, show a toast with the TextView text
    Country country = (Country) parent.getItemAtPosition(position);
    Toast.makeText(getApplicationContext(),
      country.getCode(), Toast.LENGTH_SHORT).show();
   }
  });

  listView.setOnScrollListener(new OnScrollListener(){

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

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

   int lastInScreen = firstVisibleItem + visibleItemCount;    
   if((lastInScreen == totalItemCount) && !(loadingMore)){     
    String url = "http://10.0.2.2:8080/CountryWebService" + 
     "/CountryServlet";
    grabURL(url); 
   }
   }
  });

  String url = "http://example.com";
  grabURL(url); 

 }

 public void grabURL(String url) {
  Log.v("Android Spinner JSON Data Activity", url);
  new GrabURL().execute(url);
 }

 private class GrabURL extends AsyncTask<String, Void, String> {
  private static final int REGISTRATION_TIMEOUT = 3 * 1000;
  private static final int WAIT_TIMEOUT = 30 * 1000;
  private final HttpClient httpclient = new DefaultHttpClient();
  final HttpParams params = httpclient.getParams();
  HttpResponse response;
  private String content =  null;
  private boolean error = false;
  private ProgressDialog dialog = 
   new ProgressDialog(AndroidListViewLoadMoreActivity.this);

  protected void onPreExecute() {
   dialog.setMessage("Getting your data... Please wait...");
   dialog.show();
  }

  protected String doInBackground(String... urls) {

   String URL = null;
   loadingMore = true;

   try {

   URL = urls[0];
   HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
   HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
   ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

   HttpPost httpPost = new HttpPost(URL);

   //add name value pair for the country code
   List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
   nameValuePairs.add(new BasicNameValuePair("page",String.valueOf(page)));

   httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
   response = httpclient.execute(httpPost);

    StatusLine statusLine = response.getStatusLine();
    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     response.getEntity().writeTo(out);
     out.close();
     content = out.toString();
    } else{
     //Closes the connection.
     Log.w("HTTP1:",statusLine.getReasonPhrase());
     response.getEntity().getContent().close();
     throw new IOException(statusLine.getReasonPhrase());
    }
   } catch (ClientProtocolException e) {
    Log.w("HTTP2:",e );
    content = e.getMessage();
    error = true;
    cancel(true);
   } catch (IOException e) {
    Log.w("HTTP3:",e );
    content = e.getMessage();
    error = true;
    cancel(true);
   }catch (Exception e) {
    Log.w("HTTP4:",e );
    content = e.getMessage();
    error = true;
    cancel(true);
   }

   return content;
  }

  protected void onCancelled() {
   dialog.dismiss();
   Toast toast = Toast.makeText(AndroidListViewLoadMoreActivity.this, 
     "Error connecting to Server", Toast.LENGTH_LONG);
   toast.setGravity(Gravity.TOP, 25, 400);
   toast.show();

  }

  protected void onPostExecute(String content) {
   dialog.dismiss();
   Toast toast;
   if (error) {
    toast = Toast.makeText(AndroidListViewLoadMoreActivity.this, 
      content, Toast.LENGTH_LONG);
    toast.setGravity(Gravity.TOP, 25, 400);
    toast.show();
   } else {
    displayCountryList(content);
   }
  }

 }

 private void displayCountryList(String response){

  JSONObject responseObj = null; 

  try {

   Gson gson = new Gson();
   responseObj = new JSONObject(response); 
   JSONArray countryListObj = responseObj.getJSONArray("countryList");

   //countryList = new ArrayList<Country>();
   if(countryListObj.length() == 0){
    ListView listView = (ListView) findViewById(R.id.listView1);
    listView.removeFooterView(loadMoreView);
   }
   else {
    for (int i=0; i<countryListObj.length(); i++){
    //get the country information JSON object
    String countryInfo = countryListObj.getJSONObject(i).toString();
    //create java object from the JSON object
    Country country = gson.fromJson(countryInfo, Country.class);
    //add to country array list
    countryList.add(country);
    dataAdapter.add(country);
    }
         page++;
    dataAdapter.notifyDataSetChanged();
    loadingMore = false;
   }

  } catch (JSONException e) {
   e.printStackTrace();
  }

 } 

}

将MyCustomAdapter.java设为适配器

private class MyCustomAdapter extends ArrayAdapter<Country> {

  private ArrayList<Country> countryList;

  public MyCustomAdapter(Context context, int textViewResourceId, 
    ArrayList<Country> countryList) {
   super(context, textViewResourceId, countryList);
   this.countryList = new ArrayList<Country>();
   this.countryList.addAll(countryList);
  }

  private class ViewHolder {
   TextView code;
   TextView name;
   TextView continent;
   TextView region;
  }

  public void add(Country country){
   Log.v("AddView", country.getCode());
   this.countryList.add(country);
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

   ViewHolder holder = null;
   Log.v("ConvertView", String.valueOf(position));
   if (convertView == null) {

   LayoutInflater vi = (LayoutInflater)getSystemService(
     Context.LAYOUT_INFLATER_SERVICE);
   convertView = vi.inflate(R.layout.country_info, null);

   holder = new ViewHolder();
   holder.code = (TextView) convertView.findViewById(R.id.code);
   holder.name = (TextView) convertView.findViewById(R.id.name);
   holder.continent = (TextView) convertView.findViewById(R.id.continent);
   holder.region = (TextView) convertView.findViewById(R.id.region);

   convertView.setTag(holder);

   } else {
    holder = (ViewHolder) convertView.getTag();
   }

   Country country = this.countryList.get(position);
   holder.code.setText(country.getCode());
   holder.name.setText(country.getName());
   holder.continent.setText(country.getContinent());
   holder.region.setText(country.getRegion());

   return convertView;

  }

 }
}

将Country.Java创建为pojo -

public class Country {

 String code = null;
 String name = null;
 String continent = null;
 String region = null;
 Double lifeExpectancy = null;
 Double gnp = null;
 Double surfaceArea = null;
 int population = 0;

 public String getCode() {
  return code;
 }
 public void setCode(String code) {
  this.code = code;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getContinent() {
  return continent;
 }
 public void setContinent(String continent) {
  this.continent = continent;
 }
 public String getRegion() {
  return region;
 }
 public void setRegion(String region) {
  this.region = region;
 }
 public Double getLifeExpectancy() {
  return lifeExpectancy;
 }
 public void setLifeExpectancy(Double lifeExpectancy) {
  this.lifeExpectancy = lifeExpectancy;
 }
 public Double getGnp() {
  return gnp;
 }
 public void setGnp(Double gnp) {
  this.gnp = gnp;
 }
 public Double getSurfaceArea() {
  return surfaceArea;
 }
 public void setSurfaceArea(Double surfaceArea) {
  this.surfaceArea = surfaceArea;
 }
 public int getPopulation() {
  return population;
 }
 public void setPopulation(int population) {
  this.population = population;
 }

}

为主布局创建main.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:layout_width="fill_parent"
  android:layout_height="wrap_content" android:padding="10dp"
  android:text="@string/some_text" android:textSize="20sp" />

 <ListView android:id="@+id/listView1" android:layout_width="fill_parent"
  android:layout_height="fill_parent" />

</LinearLayout>

创建country_info.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="6dip" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Code: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="Name: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:text="Continent: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:text="Region: "
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/continent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView3"
        android:layout_alignBottom="@+id/textView3"
        android:layout_toRightOf="@+id/textView3"
        android:text="TextView" />

    <TextView
        android:id="@+id/region"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView4"
        android:layout_alignBottom="@+id/textView4"
        android:layout_alignLeft="@+id/continent"
        android:text="TextView" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView3"
        android:layout_toRightOf="@+id/textView3"
        android:text="TextView" />

    <TextView
        android:id="@+id/code"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView2"
        android:layout_alignLeft="@+id/name"
        android:text="TextView" />

</RelativeLayout>

页脚视图文本 - loadmore.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:gravity="center_horizontal"
    android:padding="3dp"
    android:layout_height="fill_parent"> 

    <TextView
        android:id="@id/android:empty"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:padding="5dp"
        android:text="Loading more data..."/>

</LinearLayout>

不要忘记用 -

提及互联网许可
<uses-permission android:name="android.permission.INTERNET" />

答案 2 :(得分:1)

首先,你需要一个像这样的OnScrollListener方法:

private OnScrollListener onScrollListener() {
    return new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            int threshold = 1;
            int count = listView.getCount();

            if (scrollState == SCROLL_STATE_IDLE) {
                if (listView.getLastVisiblePosition() >= count - threshold && pageCount < 2) {
                    Log.i(TAG, "loading more data");
                    // Execute LoadMoreDataTask AsyncTask
                    //It reached ListView bottom
                    getDataFromUrl(url_page2);
                }
            }
        }

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

    };
}

listView.setOnScrollListener(onScrollListener());

设置列表视图滚动侦听器

我有一个完整的教程帖子HERE!你可以访问它!