当前位置: 首页 > 知识库问答 >
问题:

如何在android中Recylerview中显示更多内容[副本]

虞华翰
2023-03-14

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

下面是我的片段类,我在其中显示了回收器视图:

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个答案

牧献
2023-03-14

我实现类似的方法是,我在recyclerView中添加了一个名为“load more”的页脚,然后单击load more页脚,我再次调用一个服务来获取更多数据,然后通知recyclerView重新填充数据。

所以让我来讨论一下我的服务器端实现。第一次加载recyclerView时,我调用了一个服务来从页码为0的服务器获取数据。当收到响应时,我填充了RecolyerView并在RecolyerView的末尾添加了一个load more页脚。单击load more footer后,我再次调用了页码为1的服务,当我返回响应时,我用以前保存的列表追加数据,然后调用适配器上的NotifyDataSetChanged。在我的例子中,这就是简单分页的方式。

我必须放置一个boolean,它会在服务器的每个响应中返回,以指示是否还有其他数据要显示。因此,当布尔值hasnext被发现为false时,我必须将load more footer的文本更改为“no more results to show”,这样用户就可以理解没有更多数据了。

现在,您可以在RecyclerView中添加页脚

 类似资料:
  • 我正在用angularJs和highChartsJS做一个统计图。 这里是代码angularJS: Html代码: 测试代码后,我遇到了一个问题: 未捕获错误:Highcharts错误#14:www.Highcharts。com/errors/14 at对象。a、 错误(http://code.highcharts.com/highcharts.js:10:49)在k.setData(http:/

  • 我有一个很大的数组,它有很多元素,我需要在控制台中显示它,我使用console.log(),但只显示了一部分。 如何显示完整的内容?

  • 嗨,我创建了一个简单的应用程序来在webview中显示html页面,我使用webview并显示页面加载时间,如下所示。 在此之后,禁用滚动,并使用next和previous按钮来后退和前进Contain。下面是我的代码。 首先,在创建、显示、添加webview并加载html文件。 之后,使用MyWebclient类获取MainWebView的高度和宽度。 之后,使用myPictureClass获取

  • 我想在CMD窗口中显示文本文件的内容。此外,我希望看到添加到文件中的新行,如Unix中的tail-f命令。

  • 我有经纬度存储在数据库中,但我如何在地图视图中显示它,而不是每次都在浏览器上打开坐标。 我能在原生Android应用程序中显示它而不是每次都重定向到谷歌地图吗?

  • 我正在测试ace-editor显示服务器上的大型文本文件。由于它吹嘘能够处理高达4百万行的文件,并且具有文本高亮显示功能,这使它成为一个很好的候选者。 我一直在努力理解Ace Editor的文档和EditSession。根据我的理解,它可以告诉ace editor从一个文件中读取并显示它。 我正在使用createEditSessiont()创建会话并指定文档。在api文档中: createEdit