Android - 如何在listview中实现无限滚动

时间:2015-11-09 17:39:35

标签: android

这是破旧。我创建了一个滑动选项卡应用程序,并在每个片段上包含json。我正在尝试实现Endless Scroll Listener:https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews,以便在加载时向列表视图中显示只有一定数量的项目,并且当您向下滚动时会出现更多项目。

然而,我被卡住了。我不确定如何实现/使用这个类(public boolean onLoadMore(int page,int totalItemsCount)等)。我在stackoverflow中读到了另一篇关于此的帖子,但我无法弄清楚如何使它工作。任何有关如何使用它的建议或想法将不胜感激。

我包含了我的列表适配器,我的一个片段,endlessrollisterner类。我最初的尝试是在此行之后的public void onActivityCreated中包含此方法:listView =(ListView)getView()。findViewById(R.id.list);

EndlessScrollListener:

 import android.widget.AbsListView;
 public abstract class EndlessScrollListener implements AbsListView.OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;

public EndlessScrollListener() {
}

public EndlessScrollListener(int visibleThreshold) {
    this.visibleThreshold = visibleThreshold;
}

public EndlessScrollListener(int visibleThreshold, int startPage) {
    this.visibleThreshold = visibleThreshold;
    this.startingPageIndex = startPage;
    this.currentPage = startPage;
}

// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
    // If the total item count is zero and the previous isn't, assume the
    // list is invalidated and should be reset back to initial state
    if (totalItemCount < previousTotalItemCount) {
        this.currentPage = this.startingPageIndex;
        this.previousTotalItemCount = totalItemCount;
        if (totalItemCount == 0) { this.loading = true; }
    }
    // If it's still loading, we check to see if the dataset count has
    // changed, if so we conclude it has finished loading and update the current page
    // number and total item count.
    if (loading && (totalItemCount > previousTotalItemCount)) {
        loading = false;
        previousTotalItemCount = totalItemCount;
        currentPage++;
    }

    // If it isn't currently loading, we check to see if we have breached
    // the visibleThreshold and need to reload more data.
    // If we do need to reload some more data, we execute onLoadMore to fetch the data.
    if (!loading && (totalItemCount - visibleItemCount)<=(firstVisibleItem + visibleThreshold)) {
        loading = onLoadMore(currentPage + 1, totalItemCount);
    }
}

// Defines the process for actually loading more data based on page
// Returns true if more data is being loaded; returns false if there is no more data to load.
public abstract boolean onLoadMore(int page, int totalItemsCount);

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
    // Don't take any action on changed
}
}

CustomListAdapter代码:

 public class CustomListAdapter extends BaseAdapter {
 private Activity activity;
 private LayoutInflater inflater;
 private List<Tanga> tangasItems;
 ImageLoader imageLoader = AppController.getInstance().getImageLoader();

 public CustomListAdapter(Activity activity, List<Tanga> movieItems) {
this.activity = activity;
this.tangasItems = movieItems;
}

@Override
 public int getCount() {
return tangasItems.size();
}

@Override
public Object getItem(int location) {
return tangasItems.get(location);
 }

@Override
public long getItemId(int position) {
return position;
 }

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

if (inflater == null)
    inflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
    convertView = inflater.inflate(R.layout.list_row, null);

TextView name = (TextView) convertView.findViewById(R.id.name);

// getting movie data for the row
Tanga m = tangasItems.get(position);

// title
name.setText(m.getName());

return convertView;
}

 }

片段:

 public class Tab1 extends Fragment {
 private static final String url = "website.json";
 private List<Tanga> tangaList = new ArrayList<Tanga>();
 private ListView listView;
 private CustomListAdapter adapter;

 @Override
 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
 }

 public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);

listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), tangaList);
listView.setAdapter(adapter);
JsonArrayRequest movieReq = new JsonArrayRequest(url,
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                // Parsing json
                for (int i = 0; i < response.length(); i++) {
                    try {

                        JSONObject obj = response.getJSONObject(i);
                        Tanga movie = new Tanga();

                        //name
                        String name = obj.getString("name");
                        movie.setName(name);


                        // adding movie to movies array
                        tangaList.add(movie);

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

                // notifying list adapter about data changes
                // so that it renders the list view with updated data
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d("Error: ");

    }
});

// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
 }

 @Override
 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tabs, container, false);

return v;
 }
 }

0 个答案:

没有答案