如何在Android中的Recylerview中显示更多内容

时间:2016-03-16 03:18:27

标签: android

我正在开发一个应用程序,其中有recyclelerview,我必须在底部显示更多用户滚动加载更多数据。请帮我解决这个问题。

这是我的片段类,我在其中显示了Recycler View:

public class CDealAppListing extends Fragment {
    public static String m_DealListingURL = "http://192.143.0.110:8080/ireward/rest/json/metallica/getDealListInJSON";
    public static String s_szresult = " ";
    public static RecyclerView m_RecyclerView;
    public static CDealAppListingAdapter m_oAdapter;
    public static CDealAppDatastorage item;
    public ArrayList<CDealAppDatastorage> s_oDataset;
    public int[] m_n_FormImage;
    public View m_Main;
    public CRegistrationSessionManagement m_oSessionManagement;
    public String m_szMobileNumber, m_szEncryptedPassword;
    public LinearLayoutManager mLayoutManager;
    public RelativeLayout loadProgress;
    public AppCompatButton m_showMore;
    public ProgressBar mProgressBar;
    int r = 4;
    int u = 0;
    String record = String.valueOf(r);
    String last = String.valueOf(u);
    //declare boolean
    private CJsonsResponse m_oJsonsResponse;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        m_Main = inflater.inflate(R.layout.deal_app_listing, container, false);//intialize mainLayout
        new CDealDataSent().execute(m_DealListingURL);
        init();//initialize method
        implementScroll();
        return m_Main;
    }

    public void init() {
        mProgressBar = (ProgressBar) m_Main.findViewById(R.id.progressBar1);
        mProgressBar.setVisibility(View.GONE);

        m_showMore = (AppCompatButton) m_Main.findViewById(R.id.show_more);
        m_showMore.setBackgroundColor(Color.TRANSPARENT);
        m_showMore.setVisibility(View.INVISIBLE);
        // Getting the string array from strings.xml
        m_n_FormImage = new int[]{
                R.drawable.amazon,
                R.drawable.whatsapp,
                R.drawable.zorpia,
                R.drawable.path,
                R.drawable.app_me,
                R.drawable.evernote,
                R.drawable.app_me};

        m_RecyclerView = (RecyclerView) m_Main.findViewById(R.id.my_recycler_view);//finding id of recyclerview
        m_RecyclerView.setItemAnimator(new DefaultItemAnimator());//setting default animation to recyclerview
        m_RecyclerView.setHasFixedSize(true);//fixing size of recyclerview

        //Layout manager for Recycler view
        mLayoutManager = new LinearLayoutManager(getActivity());
        m_RecyclerView.setLayoutManager(mLayoutManager);//showing odata vertically to user.

        m_oSessionManagement = new CRegistrationSessionManagement(getActivity());
        HashMap<String, String> user = m_oSessionManagement.getRegistrationDetails();
        m_szEncryptedPassword = user.get(m_oSessionManagement.s_szKEY_PASSWORD);
        m_szMobileNumber = user.get(m_oSessionManagement.s_szKEY_MOBILENUMBER);
    }

    public void implementScroll() {
        m_RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (dy > 0) {
                    m_showMore.setVisibility(View.VISIBLE);
                    m_showMore.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //change boolean value
                            m_showMore.setVisibility(View.INVISIBLE);
                            r = r + 4;
                            u = u + 4;
                            record = String.valueOf(r);
                            last = String.valueOf(u);
                            new DealNext().execute(m_DealListingURL);
                        }
                    });
                } else {
                    m_showMore.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    //sending deal data to retreive response from server
    public String DealListing(String url, CRegistrationDataStorage login) {
        InputStream inputStream = null;
        m_oJsonsResponse = new CJsonsResponse();
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
            String json = "";
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("agentCode", "989899999");
            jsonObject.put("pin", "05E0901648FD6439207FA74FC3E07734");
            jsonObject.put("recordcount", record);
            jsonObject.put("lastcountvalue", last);
            //jsonObject.put("emailId", "nirajk1190@gmail.com");
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity
            httpPost.setEntity(se);
            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            // 9. receive response as inputStream
            inputStream = entity.getContent();
            System.out.println("InputStream....:" + inputStream.toString());
            System.out.println("Response....:" + httpResponse.toString());

            StatusLine statusLine = httpResponse.getStatusLine();
            System.out.println("statusLine......:" + statusLine.toString());
            ////Log.d("resp_body", resp_body.toString());
            int statusCode = statusLine.getStatusCode();
            // 10. convert inputstream to string
            if (statusCode == 200) {
                // 10. convert inputstream to string
                if (inputStream != null)
                    s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
                //String resp_body =
                EntityUtils.toString(httpResponse.getEntity());
            } else
                s_szresult = "Did not work!";
        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }
        System.out.println("resul.....:" + s_szresult);
        // 11. return s_szResult
        return s_szresult;
    }

    //  sending deal data to server and retreive response......
    class CDealDataSent extends AsyncTask<String, Void, String> {
        public JSONObject m_oResponseobject;
        public ProgressDialog m_PDialog;
        public CRegistrationDataStorage oRegisterStorage;
        public CDealAppDatastorage item;

        //      @Override
        protected void onPreExecute() {
            super.onPreExecute();
            m_PDialog = new ProgressDialog(getActivity());
            m_PDialog.setMessage("Please wait while Loading Deals...");
            m_PDialog.setCancelable(false);
            m_PDialog.show();
        }

        @Override
        protected String doInBackground(String... urls) {
            return DealListing(urls[0], oRegisterStorage);// sending data to server...

        }

        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {

            m_PDialog.dismiss();
            try {
                m_oResponseobject = new JSONObject(result);// getting response from server
                final JSONArray posts = m_oResponseobject.optJSONArray("dealList");

                s_oDataset = new ArrayList<CDealAppDatastorage>();
                for (int i = 0; i < posts.length(); i++) {
                    JSONObject post = posts.getJSONObject(i);
                    item = new CDealAppDatastorage();
                    item.setM_szHeaderText(post.getString("dealname"));
                    item.setM_szsubHeaderText(post.getString("dealcode"));
                    item.setM_n_Image(m_n_FormImage[i]);
                    s_oDataset.add(item);

                }
                if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {

                    m_oAdapter = new CDealAppListingAdapter(s_oDataset);//creating object of adapter and addd setting odata to adapter for use.
                    m_RecyclerView.setAdapter(m_oAdapter);//adding adapter to recyclerview
                } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
                    Toast.makeText(getActivity(), "Connection not avaliable", Toast.LENGTH_SHORT).show();
                }
                System.out.println("agentCode...." + m_szMobileNumber);
                System.out.println("password...." + m_szEncryptedPassword);
                System.out.println("record////" + record);
                System.out.println("last:........" + last);

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

    }
    private class DealNext extends AsyncTask<String, Void, String> {
        public JSONObject m_oResponseobject;
        public CRegistrationDataStorage oRegisterStorage;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            mProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... urls) {
            //My Background tasks are written here

            synchronized (this) {

                return DealListing(urls[0], oRegisterStorage);
            }
        }
        @Override
        protected void onPostExecute(String result) {
            mProgressBar.setVisibility(View.INVISIBLE);
            super.onPostExecute(result);
            try {
                m_oResponseobject = new JSONObject(result);// getting response from server
                final JSONArray posts = m_oResponseobject.optJSONArray("dealList");

                s_oDataset = new ArrayList<CDealAppDatastorage>();
                for (int i = 0; i < posts.length(); i++) {
                    JSONObject post = posts.getJSONObject(i);
                    item = new CDealAppDatastorage();
                    item.setM_szHeaderText(post.getString("dealname"));
                    item.setM_szsubHeaderText(post.getString("dealcode"));
                    item.setM_n_Image(m_n_FormImage[i]);
                    s_oDataset.add(item);

                }
                if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {

                    m_oAdapter = new CDealAppListingAdapter(s_oDataset);//creating object of adapter and addd setting odata to adapter for use.
                    m_RecyclerView.setAdapter(m_oAdapter);//adding adapter to recyclerview
                } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
                    Toast.makeText(getActivity(), "Connection not avaliable", Toast.LENGTH_SHORT).show();
                }
                System.out.println("agentCode...." + m_szMobileNumber);
                System.out.println("password...." + m_szEncryptedPassword);
                System.out.println("record////" + record);
                System.out.println("last:........" + last);

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


And here is Adapter class:-

    public class CDealAppListingAdapter extends RecyclerView.Adapter<CDealAppListingAdapter.DealAppViewHolder> {
    private static ArrayList<CDealAppDatastorage> s_oDataset;

    public CDealAppListingAdapter(ArrayList<CDealAppDatastorage> mDataList) {
        s_oDataset = mDataList;

    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @Override
    public DealAppViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.deallisting_card_view, viewGroup, false);
        DealAppViewHolder viewHolder = new DealAppViewHolder(itemLayoutView);//creating object of ViewHolder containg component
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(DealAppViewHolder viewHolder, int i) {
        CDealAppDatastorage list = s_oDataset.get(i);// receiving item on position on index i
        DealAppViewHolder.s_szAppImage.setImageResource(list.getM_n_Image());//adding m_n_Image to viewHolder
        DealAppViewHolder.s_szheadingText.setText(list.getM_szHeaderText());
        DealAppViewHolder.s_szSubHeader.setText(list.getM_szsubHeaderText());
        viewHolder.m_oDealAppDatastorage = list;

    }

    @Override
    public int getItemCount() {
        return (null != s_oDataset ? s_oDataset.size() : 0);//counting size of odata in ArrayList
    }

    public static class DealAppViewHolder extends RecyclerView.ViewHolder {
        public static ImageView s_szAppImage;
        public static TextView s_szheadingText, s_szSubHeader;
        public static Button s_szGetDealBtn;
        public CDealAppDatastorage m_oDealAppDatastorage;

        public DealAppViewHolder(View itemLayoutView) {
            super(itemLayoutView);
            s_szheadingText = (TextView) itemLayoutView.findViewById(R.id.headingText);// finding id of headerText...
            s_szSubHeader = (TextView) itemLayoutView.findViewById(R.id.subHeaderText);// finding id of subHeader.....
            s_szAppImage = (ImageView) itemLayoutView.findViewById(R.id.appImage);//finding Id of Imgae in CardView
            s_szGetDealBtn = (Button) itemLayoutView.findViewById(R.id.getDealBtn);// finding id of getdeal Btn

            Random rnd = new Random();//creating object of Random class
            int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));//genrating random color
            s_szGetDealBtn.setBackgroundColor(color);//backgraound color of getDeal Btn
            s_szGetDealBtn.setOnClickListener(new View.OnClickListener() {// onclick getDeal Btn
                @Override
                public void onClick(View v) {//send to deal detail page onclick getDeal Btn
                    Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
                    Bundle b = new Bundle();
                    b.putSerializable("DATA", s_oDataset.get(getPosition()));// sending data to deal detail page
                    i.putExtras(b);
                    v.getContext().startActivity(i);
                }
            });

            itemLayoutView.setOnClickListener(new View.OnClickListener() {// onclick cardview
                @Override
                public void onClick(View v) {// onclick cardview send to deal app listing details page .....
                    Intent i = new Intent(v.getContext(), CDealAppListingDetails.class);
                    Bundle b = new Bundle();
                    b.putSerializable("DATA", s_oDataset.get(getPosition()));
                    i.putExtras(b);
                    v.getContext().startActivity(i);
                }
            });

        }
    }
}

1 个答案:

答案 0 :(得分:0)

我是如何实现类似的东西的,我在名为'加载更多'的RecyclerView中添加了一个页脚,然后点击加载更多页脚我再次调用服务以获取更多数据,然后通知Recycler视图重新填充数据。

那么让我讨论一下我的服务器端实现。当第一次加载RecyclerView时,我调用了一个服务来从服务器获取页码为0的数据。当收到响应时,我填充了RecyclerView并在最后添加了一个加载更多的页脚RecyclerView。当单击加载更多页脚时,我再次使用页码1调用该服务,当我收到响应时,我将数据与先前保存的列表相加,然后在notifyDataSetChanged上调用Adapter。这就是我的情况下如何进行简单的分页。

我必须在服务器的每个响应中放置一个boolean,表明我是否还有更多数据要显示。因此,当发现布尔hasNext为false时,我必须将加载更多页脚的文本更改为“不再显示结果”,以便用户可以理解不再有数据。

Here's now you can add a footer in your RecyclerView