1

我从服务器加载一些 json 数据并将它们显示在我的应用程序中。我使用 RecyclerView。我想第一次加载 10 个项目并使用滚动加载 10 个其他项目。

我该怎么做?

我正在使用本教程,这一点我无法将教程与我的代码 recyclerview 加载更多

更新

这是我的活动代码

public class NewsActivity extends AppCompatActivity {


    //--------------------------------
    private ProgressDialog pDialog;
    //----------------------------------
    private String urlJsonArray="http://kazeroon.mosbate16.com/news/news.php";
    private static String TAG = ListActivity.class.getSimpleName();
    static List<News> mNews = new ArrayList<>();
    private int page=0;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


//-------------
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(true);
        //----------------
        if (isOnline()==true) {
            makeJsonArrayRequest_News();


        }else
            Toast.makeText(getApplicationContext(),
                    "برای دریافت اطلاعات به اینترنت نیاز دارید.",
                    Toast.LENGTH_LONG).show();

    }
    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }
    private void makeJsonArrayRequest_News() {
        showpDialog();



        RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
        StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //This code is executed if the server responds, whether or not the response contains data.
                //The String 'response' contains the server's response.
                try {
                    JSONArray jsonArray = new JSONArray(response);

                    for (int i = 0; i < jsonArray.length(); i++) {
                        News news = new News();

                        JSONObject jsonObj = jsonArray.getJSONObject(i);

                        String id = jsonObj.getString("id");
                        String title = jsonObj.getString("title");
                        String shortcontent = jsonObj.getString("shortcontent");
                        String longcontent = jsonObj.getString("longcontent");
                        String publicationdate = jsonObj.getString("publicationdate");
                        String pic = jsonObj.getString("pic");
                        String diffdate = jsonObj.getString("diffdate");
                        String src = jsonObj.getString("src");
                        String link = jsonObj.getString("link");


                        news.setId(id);
                        news.setTitle(title);
                        news.setShortContent(shortcontent);
                        news.setLongContent(longcontent);
                        news.setPublicationDate(publicationdate);
                        news.setPic(pic);
                        news.setDiffDate(diffdate);
                        news.setSrc(src);
                        news.setLink(link);
                        mNews.add(news);


                    }
                    RecyclerView recyclerViewlist = (RecyclerView) findViewById(R.id.newsList);
                    //tarif layout maneger baraye tarif noe nemayesh
                    recyclerViewlist.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
                    //tarif class adapter recyclview
                    final RVAdapterNews ad = new RVAdapterNews(NewsActivity.this, mNews, recyclerViewlist);
                    recyclerViewlist.setAdapter(ad);
                    ad.setOnLoadMoreListener(new ir.kazeroonsara.kazeroon.OnLoadMoreListener() {
                        @Override
                        public void onLoadMore() {
                            Log.e("haint", "Load More");
                            mNews.add(null);
                            ad.notifyItemInserted(mNews.size() - 1);

                            //Load more data for reyclerview
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Log.e("haint", "Load More 2");

                                    //Remove loading item
                                    mNews.remove(mNews.size() - 1);
                                    ad.notifyItemRemoved(mNews.size());

                                    //Load data
                                    //-----------------------------------------------------------------------------------------------
                                    RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
                                    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
                                        @Override
                                        public void onResponse(String response) {
                                            //This code is executed if the server responds, whether or not the response contains data.
                                            //The String 'response' contains the server's response.
                                            try {
                                                JSONArray jsonArray = new JSONArray(response);

                                                for (int i = 0; i < jsonArray.length(); i++) {
                                                    News news = new News();

                                                    JSONObject jsonObj = jsonArray.getJSONObject(i);

                                                    String id = jsonObj.getString("id");
                                                    String title = jsonObj.getString("title");
                                                    String shortcontent = jsonObj.getString("shortcontent");
                                                    String longcontent = jsonObj.getString("longcontent");
                                                    String publicationdate = jsonObj.getString("publicationdate");
                                                    String pic = jsonObj.getString("pic");
                                                    String diffdate = jsonObj.getString("diffdate");
                                                    String src = jsonObj.getString("src");
                                                    String link = jsonObj.getString("link");


                                                    news.setId(id);
                                                    news.setTitle(title);
                                                    news.setShortContent(shortcontent);
                                                    news.setLongContent(longcontent);
                                                    news.setPublicationDate(publicationdate);
                                                    news.setPic(pic);
                                                    news.setDiffDate(diffdate);
                                                    news.setSrc(src);
                                                    news.setLink(link);
                                                    mNews.add(news);


                                                }






                                            } catch (JSONException e) {
                                                Toast.makeText(getApplicationContext(),
                                                        "ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
                                                        Toast.LENGTH_LONG).show();                        }
                                            hidepDialog();



                                        }
                                    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
                                        @Override
                                        public void onErrorResponse(VolleyError error) {
                                            //This code is executed if there is an error.
                                            Toast.makeText(getApplicationContext(),
                                                    "مشکلی در دریافت اطلاعات وجود دارد",
                                                    Toast.LENGTH_LONG).show();
                                        }
                                    }) {
                                        protected Map<String, String> getParams() {
                                            Map<String, String> MyData = new HashMap<String, String>();
                                            page=page+1;
                                            MyData.put("page", String.valueOf(page));
                                            return MyData;
                                        }
                                    };

                                    MyRequestQueue.add(MyStringRequest);
                                    //----------------------------------------------------------------------------------------------

                                    ad.notifyDataSetChanged();
                                    ad.setLoaded();
                                }
                            }, 5000);
                        }
                    });




                } catch (JSONException e) {
                    Toast.makeText(getApplicationContext(),
                            "ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
                            Toast.LENGTH_LONG).show();                        }
                hidepDialog();



            }
        }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
            @Override
            public void onErrorResponse(VolleyError error) {
                //This code is executed if there is an error.
                Toast.makeText(getApplicationContext(),
                        "مشکلی در دریافت اطلاعات وجود دارد",
                        Toast.LENGTH_LONG).show();
            }
        }) {
            protected Map<String, String> getParams() {
                Map<String, String> MyData = new HashMap<String, String>();
                MyData.put("page", String.valueOf(page));
                return MyData;
            }
        };

        MyRequestQueue.add(MyStringRequest);


    }
    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
    public interface OnLoadMoreListener {
        void onLoadMore();
    }
}

这是我的代码适配器

public class RVAdapterNews extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    //consteraktor ra misazim
    private final int VIEW_TYPE_ITEM = 0;
    private final int VIEW_TYPE_LOADING = 1;
    private OnLoadMoreListener mOnLoadMoreListener;
    private boolean isLoading;
    private int visibleThreshold = 5;
    private int lastVisibleItem, totalItemCount;
    private Context context;
    private LayoutInflater inflater;
    List<News> mNews;
    News news=new News();
    private  RecyclerView mRecyclerViewlist;


    public RVAdapterNews(final NewsActivity context, List<News> mNews,RecyclerView recyclerViewlist){
        this.context=context;
        this.inflater=LayoutInflater.from(context);
        this.mNews=mNews;
        this.mRecyclerViewlist=recyclerViewlist;
        //-------------------------------------------------
        final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerViewlist.getLayoutManager();
        mRecyclerViewlist.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                totalItemCount = linearLayoutManager.getItemCount();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();

                if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                    if (mOnLoadMoreListener != null) {
                        mOnLoadMoreListener.onLoadMore();
                    }
                    isLoading = true;

                }
            }
        });


    }
    @Override
    public int getItemViewType(int position) {
        //return super.getItemViewType(position);
        return mNews.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;

    }
    //--------------------------------------------------------MyViewHolder----------------------------------------------
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //bayad aval yek layout besazim - recycler_layout
        //layout ro moarefi mikonim
        //View v=inflater.inflate(R.layout.rvnews_layout,parent,false);
        // vh=new MyViewHolder(v);
        //return vh;

        if (viewType == VIEW_TYPE_ITEM) {
            View view = LayoutInflater.from(context).inflate(R.layout.rvnews_layout, parent, false);
            MyViewHolder vh=new MyViewHolder(view);
            return vh;
        } else if (viewType == VIEW_TYPE_LOADING) {
            View view = LayoutInflater.from(context).inflate(R.layout.layout_loading_item, parent, false);
            LoadingViewHolder vh2=new LoadingViewHolder(view);
            return vh2;
        }
        return null;
    }

    //--------------------------------MyViewHolder holder------------------------------------------------------------
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        //itemhaei ke bayad neshan dadeh shavad bayad inja vared shavad
        if (holder instanceof MyViewHolder) {
            news = mNews.get(position);
            final MyViewHolder myViewHolder = (MyViewHolder) holder;
            myViewHolder.newsTitle.setText(news.getTitle());
            //----------------------
            long seconds = Long.parseLong(news.getDiffDate());
            //int day = (int) TimeUnit.SECONDS.toDays(seconds);
            //long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
            //long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
            //long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
            long minute = seconds / 60;
            long hours = minute / 60;
            int day = (int) hours / 24;
            int week = day / 7;
            int month = day / 30;
            int year = day / 365;


            if (seconds < 60)
                myViewHolder.newsDatePublication.setText(seconds + " ثانیه قبل");
            else if (seconds >= 60 && seconds < 3600)
                myViewHolder.newsDatePublication.setText(minute + " دقیقه قبل");
            else if (seconds >= 3600 && seconds < 86400)
                myViewHolder.newsDatePublication.setText(hours + " ساعت قبل");
            else if (seconds >= 86400 && seconds < 604800)
                myViewHolder.newsDatePublication.setText(day + " روز قبل");
            else if (seconds >= 604800 && seconds < 2629743)
                myViewHolder.newsDatePublication.setText(week + " هفته قبل");
            else if (seconds >= 2629743 && seconds < 31556926)
                myViewHolder.newsDatePublication.setText(month + " ماه قبل");
            else
                myViewHolder.newsDatePublication.setText(year + " سال قبل");


            //----------------------
            //holder.newsDatePublication.setText(newsPublicationDateItems.get(position));
            Uri uri = Uri.parse(news.getPic());
            Picasso.with(context).load(uri).resize(200, 200).centerCrop().into(myViewHolder.newsPic, new com.squareup.picasso.Callback() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onError() {
                    myViewHolder.newsPic.setImageResource(R.mipmap.ic_default_list);
                }
            });
            myViewHolder.cvNews.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    News news = mNews.get(position);
                    Intent intent = new Intent(context, NewsViewActivity.class);
                    intent.putExtra("id", news.getId());
                    intent.putExtra("title", news.getTitle());
                    intent.putExtra("shortContent", news.getShortContent());
                    intent.putExtra("longContent", news.getLongContent());
                    intent.putExtra("datePublication", news.getPublicationDate());
                    intent.putExtra("pic", news.getPic());
                    intent.putExtra("src", news.getSrc());
                    intent.putExtra("link", news.getLink());


                    context.startActivity(intent);
                }
            });
        }else if (holder instanceof LoadingViewHolder) {
            LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
            loadingViewHolder.progressBar.setIndeterminate(true);
        }



    }
    @Override
    public int getItemCount() {
        //tedad itemhara baraye nemayesh midahim
        //return mNews.size();
        return mNews == null ? 0 : mNews.size();
    }



    class LoadingViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;

        public LoadingViewHolder(View itemView) {
            super(itemView);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
        }
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        //bayad ajzaye layout ro tarif konim
        ImageView newsPic;
        TextView newsTitle;
        TextView newsShortContent;
        TextView newsLongContent;
        TextView newsDatePublication;
        CardView cvNews;

        public MyViewHolder(View itemView) {
            super(itemView);
            newsPic=(ImageView) itemView.findViewById(R.id.ivNewsPic);
            newsTitle= (TextView) itemView.findViewById(R.id.txtNewsTitle);
            newsDatePublication = (TextView) itemView.findViewById(R.id.txtNewsDatePublication);
            cvNews = (CardView) itemView.findViewById(R.id.CVNews);


        }
    }

    public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
        this.mOnLoadMoreListener = mOnLoadMoreListener;
    }
    public void setLoaded() {
        isLoading = false;
    }
}

在此处输入图像描述

4

2 回答 2

2

你可以关注这个网站:recyclerview 加载更多

在教程和教程中,您应该看到有关工作示例的视频

活动代码

public class NewsActivity extends AppCompatActivity {


    //--------------------------------
    private ProgressDialog pDialog;
    //----------------------------------
    private String urlJsonArray="http://...../test.php";
    private static String TAG = ListActivity.class.getSimpleName();
    static List<News> mNews = new ArrayList<>();
    private int page=0;
    RVAdapterNews ad;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //---------------------------------------
        ActionBar mActionBar = getSupportActionBar();
        mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

        LinearLayout actionBarLayout = (LinearLayout)getLayoutInflater().inflate(R.layout.actionbar, null);
        TextView actionBarTitleview = (TextView)actionBarLayout.findViewById(R.id.tvTitleActionbar);
        //----daryafte lable activity
        ActivityInfo activityInfo = null;
        try {
            activityInfo = getPackageManager().getActivityInfo(
                    getComponentName(), PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String title = activityInfo.loadLabel(getPackageManager())
                .toString();
        //-------------------------------------
        actionBarTitleview.setText(title);
        ActionBar.LayoutParams params = new ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT,
                Gravity.RIGHT);

        mActionBar.setCustomView(actionBarLayout, params);
        mActionBar.setDisplayHomeAsUpEnabled(false);
        //------------------------------------------


//-------------
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(true);
        //----------------
        if (isOnline()==true) {
            makeJsonArrayRequest_News();


        }else
            Toast.makeText(getApplicationContext(),
                    "برای دریافت اطلاعات به اینترنت نیاز دارید.",
                    Toast.LENGTH_LONG).show();

    }
    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }
    private void makeJsonArrayRequest_News() {
        showpDialog();



        RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
        StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //This code is executed if the server responds, whether or not the response contains data.
                //The String 'response' contains the server's response.
                try {
                    JSONArray jsonArray = new JSONArray(response);

                    for (int i = 0; i < jsonArray.length(); i++) {
                        News news = new News();

                        JSONObject jsonObj = jsonArray.getJSONObject(i);

                        String id = jsonObj.getString("id");
                        String title = jsonObj.getString("title");
                        String shortcontent = jsonObj.getString("shortcontent");
                        String longcontent = jsonObj.getString("longcontent");
                        String publicationdate = jsonObj.getString("publicationdate");
                        String pic = jsonObj.getString("pic");
                        String diffdate = jsonObj.getString("diffdate");
                        String src = jsonObj.getString("src");
                        String link = jsonObj.getString("link");


                        news.setId(id);
                        news.setTitle(title);
                        news.setShortContent(shortcontent);
                        news.setLongContent(longcontent);
                        news.setPublicationDate(publicationdate);
                        news.setPic(pic);
                        news.setDiffDate(diffdate);
                        news.setSrc(src);
                        news.setLink(link);
                        mNews.add(news);


                    }
                    RecyclerView recyclerViewlist = (RecyclerView) findViewById(R.id.newsList);
                    //tarif layout maneger baraye tarif noe nemayesh
                    recyclerViewlist.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
                    //tarif class adapter recyclview
                    ad = new RVAdapterNews(NewsActivity.this, mNews, recyclerViewlist);
                    recyclerViewlist.setAdapter(ad);
                    ad.setOnLoadMoreListener(new OnLoadMoreListener() {
                        @Override
                        public void onLoadMore() {
                            Log.e("haint", "Load More");
                            mNews.add(null);
                            ad.notifyItemInserted(mNews.size() - 1);

                            //Load more data for reyclerview

                                    Log.e("haint", "Load More 2");

                                    //Remove loading item

                                    //mNews.remove(mNews.size() - 1);
                                    //ad.notifyItemRemoved(mNews.size());
                                    //ad.notifyDataSetChanged();



                                    //Load data
                                    //-----------------------------------------------------------------------------------------------
                                    RequestQueue MyRequestQueue = Volley.newRequestQueue(NewsActivity.this);
                                    StringRequest MyStringRequest = new StringRequest(Request.Method.POST, urlJsonArray, new Response.Listener<String>() {
                                        @Override
                                        public void onResponse(String response) {
                                            //This code is executed if the server responds, whether or not the response contains data.
                                            //The String 'response' contains the server's response.
                                            new Handler().postDelayed(new Runnable() {
                                                @Override
                                                public void run() {

                                                }
                                                                      },3000);
                                            Toast.makeText(getApplicationContext(), "بارگزاری اخبار بیشتر انجام شد", Toast.LENGTH_SHORT).show();

                                            //Remove loading item
                                            mNews.remove(mNews.size() - 1);
                                            ad.notifyItemRemoved(mNews.size());
                                            //ad.notifyDataSetChanged();

                                            try {
                                                JSONArray jsonArray = new JSONArray(response);

                                                for (int i = 0; i < jsonArray.length(); i++) {
                                                    News news = new News();

                                                    JSONObject jsonObj = jsonArray.getJSONObject(i);

                                                    String id = jsonObj.getString("id");
                                                    String title = jsonObj.getString("title");
                                                    String shortcontent = jsonObj.getString("shortcontent");
                                                    String longcontent = jsonObj.getString("longcontent");
                                                    String publicationdate = jsonObj.getString("publicationdate");
                                                    String pic = jsonObj.getString("pic");
                                                    String diffdate = jsonObj.getString("diffdate");
                                                    String src = jsonObj.getString("src");
                                                    String link = jsonObj.getString("link");


                                                    news.setId(id);
                                                    news.setTitle(title);
                                                    news.setShortContent(shortcontent);
                                                    news.setLongContent(longcontent);
                                                    news.setPublicationDate(publicationdate);
                                                    news.setPic(pic);
                                                    news.setDiffDate(diffdate);
                                                    news.setSrc(src);
                                                    news.setLink(link);
                                                    mNews.add(news);


                                                }
                                                ad.setLoaded();






                                            } catch (JSONException e) {
                                                Toast.makeText(getApplicationContext(),
                                                        "ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
                                                        Toast.LENGTH_LONG).show();                        }
                                            hidepDialog();



                                        }
                                    }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
                                        @Override
                                        public void onErrorResponse(VolleyError error) {
                                            //This code is executed if there is an error.
                                            Toast.makeText(getApplicationContext(),
                                                    "مشکلی در دریافت اطلاعات وجود دارد",
                                                    Toast.LENGTH_LONG).show();
                                        }
                                    }) {
                                        protected Map<String, String> getParams() {
                                            Map<String, String> MyData = new HashMap<String, String>();
                                            page=page+1;
                                            MyData.put("page", String.valueOf(page));
                                            return MyData;
                                        }
                                    };

                                    MyRequestQueue.add(MyStringRequest);


                            ad.notifyDataSetChanged();
                           // ad.setLoaded();



                        }
                    });




                } catch (JSONException e) {
                    Toast.makeText(getApplicationContext(),
                            "ارتباط با سرور برقرار نشد،آخرین اطلاعات دریافتی نمایش داده می شود",
                            Toast.LENGTH_LONG).show();                        }
                hidepDialog();



            }
        }, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
            @Override
            public void onErrorResponse(VolleyError error) {
                //This code is executed if there is an error.
                Toast.makeText(getApplicationContext(),
                        "مشکلی در دریافت اطلاعات وجود دارد",
                        Toast.LENGTH_LONG).show();
            }
        }) {
            protected Map<String, String> getParams() {
                Map<String, String> MyData = new HashMap<String, String>();
                MyData.put("page", String.valueOf(page));
                return MyData;
            }
        };

        MyRequestQueue.add(MyStringRequest);


    }
    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

}

适配器代码

public class RVAdapterNews extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    //consteraktor ra misazim
    private final int VIEW_TYPE_ITEM = 0;
    private final int VIEW_TYPE_LOADING = 1;
    private OnLoadMoreListener mOnLoadMoreListener;
    private boolean isLoading;
    private int visibleThreshold = 5;
    private int lastVisibleItem, totalItemCount;
    private Context context;
    private LayoutInflater inflater;
    List<News> mNews;
    News news=new News();
    private  RecyclerView mRecyclerViewlist;


    public RVAdapterNews(final NewsActivity context, List<News> mNews,RecyclerView recyclerViewlist){
        this.context=context;
        this.inflater=LayoutInflater.from(context);
        this.mNews=mNews;
        this.mRecyclerViewlist=recyclerViewlist;
        //-------------------------------------------------
        final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerViewlist.getLayoutManager();
        mRecyclerViewlist.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                totalItemCount = linearLayoutManager.getItemCount();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();

                if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                    if (mOnLoadMoreListener != null) {
                        mOnLoadMoreListener.onLoadMore();
                    }
                    isLoading = true;

                }
            }
        });


    }
    @Override
    public int getItemViewType(int position) {
        //return super.getItemViewType(position);
        return mNews.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //bayad aval yek layout besazim - recycler_layout
        //layout ro moarefi mikonim
        //View v=inflater.inflate(R.layout.rvnews_layout,parent,false);
        // vh=new MyViewHolder(v);
        //return vh;

        if (viewType == VIEW_TYPE_ITEM) {
            View view = LayoutInflater.from(context).inflate(R.layout.rvnews_layout, parent, false);
            MyViewHolder vh=new MyViewHolder(view);
            return vh;
        } else if (viewType == VIEW_TYPE_LOADING) {
            View view = LayoutInflater.from(context).inflate(R.layout.layout_loading_item, parent, false);
            LoadingViewHolder vh2=new LoadingViewHolder(view);
            return vh2;
        }
        return null;
    }


    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        //itemhaei ke bayad neshan dadeh shavad bayad inja vared shavad
        if (holder instanceof MyViewHolder) {
            news = mNews.get(position);
            final MyViewHolder myViewHolder = (MyViewHolder) holder;
            myViewHolder.newsTitle.setText(news.getTitle());
            //----------------------
            long seconds = Long.parseLong(news.getDiffDate());
            //int day = (int) TimeUnit.SECONDS.toDays(seconds);
            //long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
            //long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
            //long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
            long minute = seconds / 60;
            long hours = minute / 60;
            int day = (int) hours / 24;
            int week = day / 7;
            int month = day / 30;
            int year = day / 365;


            if (seconds < 60)
                myViewHolder.newsDatePublication.setText(seconds + " ثانیه قبل");
            else if (seconds >= 60 && seconds < 3600)
                myViewHolder.newsDatePublication.setText(minute + " دقیقه قبل");
            else if (seconds >= 3600 && seconds < 86400)
                myViewHolder.newsDatePublication.setText(hours + " ساعت قبل");
            else if (seconds >= 86400 && seconds < 604800)
                myViewHolder.newsDatePublication.setText(day + " روز قبل");
            else if (seconds >= 604800 && seconds < 2629743)
                myViewHolder.newsDatePublication.setText(week + " هفته قبل");
            else if (seconds >= 2629743 && seconds < 31556926)
                myViewHolder.newsDatePublication.setText(month + " ماه قبل");
            else
                myViewHolder.newsDatePublication.setText(year + " سال قبل");


            //----------------------
            //holder.newsDatePublication.setText(newsPublicationDateItems.get(position));
            Uri uri = Uri.parse(news.getPic());
            Picasso.with(context).load(uri).resize(200, 200).centerCrop().into(myViewHolder.newsPic, new com.squareup.picasso.Callback() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onError() {
                    myViewHolder.newsPic.setImageResource(R.mipmap.ic_default_list);
                }
            });
            myViewHolder.cvNews.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    News news = mNews.get(position);
                    Intent intent = new Intent(context, NewsViewActivity.class);
                    intent.putExtra("id", news.getId());
                    intent.putExtra("title", news.getTitle());
                    intent.putExtra("shortContent", news.getShortContent());
                    intent.putExtra("longContent", news.getLongContent());
                    intent.putExtra("datePublication", news.getPublicationDate());
                    intent.putExtra("pic", news.getPic());
                    intent.putExtra("src", news.getSrc());
                    intent.putExtra("link", news.getLink());


                    context.startActivity(intent);
                }
            });
        }else if (holder instanceof LoadingViewHolder) {
            LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder;
            loadingViewHolder.progressBar.setIndeterminate(true);
        }



    }
    @Override
    public int getItemCount() {
        //tedad itemhara baraye nemayesh midahim
        //return mNews.size();
        return mNews == null ? 0 : mNews.size();
    }



    class LoadingViewHolder extends RecyclerView.ViewHolder {
        public ProgressBar progressBar;

        public LoadingViewHolder(View itemView) {
            super(itemView);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1);
        }
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        //bayad ajzaye layout ro tarif konim
        ImageView newsPic;
        TextView newsTitle;
        TextView newsShortContent;
        TextView newsLongContent;
        TextView newsDatePublication;
        CardView cvNews;

        public MyViewHolder(View itemView) {
            super(itemView);
            newsPic=(ImageView) itemView.findViewById(R.id.ivNewsPic);
            newsTitle= (TextView) itemView.findViewById(R.id.txtNewsTitle);
            newsDatePublication = (TextView) itemView.findViewById(R.id.txtNewsDatePublication);
            cvNews = (CardView) itemView.findViewById(R.id.CVNews);


        }
    }

    public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) {
        this.mOnLoadMoreListener = mOnLoadMoreListener;
    }

    public void setLoaded() {
        isLoading = false;
    }
}
于 2016-04-30T12:05:54.467 回答
2
 JsonArrayRequest req = new JsonArrayRequest(urlJsonArray,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());

                        try {
                            // Parsing json array response
                            // loop through each json object


                            for (int i = 0; i < response.length(); i++) {

                                News news = new News();


                                JSONObject person = (JSONObject) response.get(i);
                                String id = person.getString("id");
                                String title = person.getString("title");
                                String shortcontent = person.getString("shortcontent");
                                String longcontent = person.getString("longcontent");
                                String publicationdate = person.getString("publicationdate");
                                String pic = person.getString("pic");
                                String diffdate=person.getString("diffdate");
                                String src=person.getString("src");
                                String link=person.getString("link");



                                news.setId(id);
                                news.setTitle(title);
                                news.setShortContent(shortcontent);
                                news.setLongContent(longcontent);
                                news.setPublicationDate(publicationdate);
                                news.setPic(pic);
                                news.setDiffDate(diffdate);
                                news.setSrc(src);
                                news.setLongContent(link);
                                mNews.add(news);

                            }
                            RecyclerView recyclerViewlist=(RecyclerView) findViewById(R.id.newsList);
                            //tarif class adapter recyclview
                            RVAdapterNews ad=null;

if(ad==null)
{
ad=new  RVAdapterNews(NewsActivity.this,mNews);
                            recyclerViewlist.setAdapter(ad);
                            //tarif layout maneger baraye tarif noe nemayesh
                            recyclerViewlist.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
}
else
{
  ad.Add(mActivity, mNews);
}


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

                            Toast.makeText(getApplicationContext(),
                                    "error"`enter code here`,
                                    Toast.LENGTH_LONG).show();

                        }
                        hidepDialog();

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                //Toast.makeText(getApplicationContext(),
                //        error.getMessage(), Toast.LENGTH_SHORT).show();
                Toast.makeText(getApplicationContext(),
                        "error",
                        Toast.LENGTH_LONG).show();
                hidepDialog();
            }
        });

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


IN Adapter make a method Add like below


private ArrayList<News> newsall;
 public RVAdapterNews(Activity mActivity, ArrayList<News> news) {
        this.mActivity = mActivity;


      newsall.addAll(news);
        notifyDataSetChanged();
    }
于 2016-04-30T13:04:23.313 回答