如何在Recyclerview上无限滚动?

时间:2016-03-03 08:58:44

标签: android adapter android-recyclerview android-cardview

主要的activty.java 我正在使用排球库。 在这里我要做的是在卡片视图上加载10张图像,直到用户到达最后

public class MainActivity extends ActionBarActivity {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    String loginURL="http://*****o.comli.com/rimgid.php";
    RequestQueue requestQueue;
    String[] title=null,url=null;
    int i=0;
    Activity activity= MainActivity.this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        requestQueue = Volley.newRequestQueue(this);
        //output = (TextView) findViewById(R.id.hi);
        JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, loginURL,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try{

                            JSONArray ja = response.getJSONArray("hi");//parsing id and image url
                            title=new String[ja.length()];
                            url=new String[ja.length()];
                            for(int i=0; i < ja.length(); i++){

                                JSONObject jsonObject = ja.getJSONObject(i);

                                // int id = Integer.parseInt(jsonObject.optString("id").toString());
                                url[i] ="http://developer.andrinfo.comli.com/img/"+ jsonObject.getInt("id")+".jpg";

                                title[i] = jsonObject.getString("name");


                            }
                            mAdapter = new MyRecyclerViewAdapter(activity,getDataSet(url,title,ja.length()));
                            mRecyclerView.setAdapter(mAdapter);
                           // Toast.makeText(getApplicationContext(),url[2],Toast.LENGTH_SHORT).show();
                            //output.setText(data);
                        }catch(JSONException e){e.printStackTrace();}
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley",error.toString());

                    }
                }
        );
        requestQueue.add(jor);

        //requestQueue.start();
        // Code to Add an item with default animation
        //((MyRecyclerViewAdapter) mAdapter).addItem(obj, index);

        // Code to remove an item with default animation
        //((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
    }




    private ArrayList<DataObject> getDataSet(String[] images,String[] headlines,int size) {
       // String[] images = getResources().getStringArray(R.array.images_array);
       //String[] headlines = getResources().getStringArray(R.array.headline_array);
        ArrayList results = new ArrayList<DataObject>();
        for (int index = 0; index < size; index++) {
            DataObject obj = new DataObject(headlines[index],
                    "Secondary " + index);
            obj.setUrl(images[index]);
            //obj.setHeadline(headlines[index]);
            results.add(index, obj);
        }
        return results;
    }
}

我的适配器类

public class MyRecyclerViewAdapter extends RecyclerView
        .Adapter<MyRecyclerViewAdapter
        .DataObjectHolder> {
    private static String LOG_TAG = "MyRecyclerViewAdapter";
    private ArrayList<DataObject> mDataset;
    private static MyClickListener myClickListener;
    private String headline;
    private String reporterName;
    private String date;
    private String url;
    private Activity activityContext;

    public static class DataObjectHolder extends RecyclerView.ViewHolder
           {
        TextView label;
        TextView dateTime;
        ImageView imageView;

        public DataObjectHolder(View itemView) {
            super(itemView);
            label = (TextView) itemView.findViewById(R.id.textView);
            dateTime = (TextView) itemView.findViewById(R.id.textView2);
            imageView=(ImageView)itemView.findViewById(R.id.imageView);
            Log.i(LOG_TAG, "Adding Listener");
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }

    }



    public MyRecyclerViewAdapter(Activity context,ArrayList<DataObject> myDataset) {
        mDataset = myDataset;
        activityContext=context;
    }

    @Override
    public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.cardview, parent, false);

        DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
        return dataObjectHolder;
    }

    @Override
    public void onBindViewHolder(DataObjectHolder holder, int position) {
        Context context=null;
        holder.label.setText(mDataset.get(position).getmText1());
        holder.dateTime.setText(mDataset.get(position).getmText2());
        Drawable placeholder = holder.imageView.getContext().getResources().getDrawable(R.drawable.placeholder);
        holder.imageView.setImageDrawable(placeholder);
        //new ImageDownloaderTask(holder.imageView).execute(mDataset.get(position).getUrl());
       Picasso.with(activityContext)
                .load(mDataset.get(position).getUrl())
                .placeholder(R.drawable.placeholder)
                .into(holder.imageView);
    }

    public void addItem(DataObject dataObj, int index) {
        mDataset.add(index, dataObj);
        notifyItemInserted(index);
    }

    public void deleteItem(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public interface MyClickListener {
        public void onItemClick(int position, View v);
    }

}

请帮我这样做。 我想将滚动侦听器与主要活动一起使用..

1 个答案:

答案 0 :(得分:0)

我使用这个类在RecyclerViews上实现无休止的滚动行为

public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
public static String TAG = EndlessRecyclerOnScrollListener.class.getSimpleName();

private int previousTotal = 0; // The total number of items in the dataset after the last load
private boolean loading = true; // True if we are still waiting for the last set of data to load.
private int visibleThreshold = 5; // The minimum amount of items to have below your current scroll position before loading more.
int firstVisibleItem, visibleItemCount, totalItemCount;

private int current_page = 1;

private LinearLayoutManager mLinearLayoutManager;

public EndlessRecyclerOnScrollListener(LinearLayoutManager linearLayoutManager) {
    this.mLinearLayoutManager = linearLayoutManager;
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);

    visibleItemCount = recyclerView.getChildCount();
    totalItemCount = mLinearLayoutManager.getItemCount();
    firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();

    if (loading) {
        if (totalItemCount > previousTotal) {
            loading = false;
            previousTotal = totalItemCount;
        }
    }
    if (!loading && (totalItemCount - visibleItemCount)
            <= (firstVisibleItem + visibleThreshold)) {
        // End has been reached

        // Do something
        current_page++;

        onLoadMore(current_page);

        loading = true;
    }
}

public abstract void onLoadMore(int current_page);

}

像这样使用:

  mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
        @Override
        public void onLoadMore(int current_page) {
            //call server
            getRestaurantReviews(current_page);
        }
    });