如何在android的Recyclerview中显示更多[重复]

Posted

技术标签:

【中文标题】如何在android的Recyclerview中显示更多[重复]【英文标题】:How to show more in Recylerview in android [duplicate] 【发布时间】:2016-07-01 18:32:21 【问题描述】:

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

这是我展示 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】:

我如何实现类似的事情是,我在RecyclerView 中添加了一个名为“加载更多”的页脚,然后通过单击加载更多页脚,我再次调用服务以获取更多数据,然后通知回收器视图重新填充数据。

所以让我讨论一下我的服务器端实现。第一次加载RecyclerView 时,我调用服务从页码为0 的服务器获取数据。收到响应后,我填充了RecyclerView,并在RecyclerView 末尾添加了一个加载更多页脚.当单击加载更多页脚时,我再次使用第 1 页调用该服务,当我收到响应时,我将数据附加到先前保存的列表中,然后在 Adapter 上调用 notifyDataSetChanged。在我的例子中,这就是一个简单的分页方式。

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

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

【讨论】:

页脚布局将在 recyclerview 布局中定义,我不知道在哪里放置页脚 而我正在添加 iy over lap recyclerview 不知道从哪里调用异步任务 您已经有一个 AsyncTask。当您从服务器获得响应时,您需要将 notifyDataSetChanged 放在 postExecute 方法中 请告诉我关于 notifydatasetchanged 的​​事

以上是关于如何在android的Recyclerview中显示更多[重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何在android的Recyclerview中显示更多[重复]

如何在 Android 的 RecyclerView 中显示来自 Firestore 的数据?

Android:如何使用 RecyclerView 实现图片库

如何在 Android Studio 中禁用 recyclerview 特定数据?

如何在 recyclerview 适配器中将动态视图添加到 android 布局

如何在android中排列RecyclerView上的数据?