Recyclerview使用改造装载更多物品

时间:2019-06-17 06:49:46

标签: android-recyclerview pagination retrofit2

我正在开发献血应用程序。用户需要选择血型和地区,并且如果他/她按下搜索按钮,则该应用需要显示带有“加载更多”选项的RecyclerView。我需要传递血型ID,地区ID以及计数和索引。在这里,索引应按计数增加。我进行了搜索,但未获得任何明确的解决方案。

请检查我的代码索引未按预期方式增加。

HomeActivity

public class Home`Activity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    //...

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

        groupSpin=findViewById(R.id.group_spinner);
        distSpin=findViewById(R.id.district_spinner);
        talukSpin=findViewById(R.id.taluk_spinner);
        search=findViewById(R.id.searchGroup_button);
        recycleList=findViewById(R.id.searchList);

        progress=findViewById(R.id.progressBar);
        text=findViewById(R.id.text_noData);

        service = ApiClient.createService(ApiCall.class, HomeActivity.this);

        pDialog=new ProgressDialog(HomeActivity.this);
        pDialog.setMessage("Loading..");
        pDialog.setCancelable(false);
        pDialog.show();

        getBloodGroups();
        getDistrict();

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(groupSpin.getText().toString().isEmpty() && distSpin.getText().toString().isEmpty()){
           //        groupSpin.setError("Blood group field is required");
                }
                else{
                    setRecyclerViewPagination();

                }   
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    private RecyclerView.OnScrollListener recycleOnScroll=new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                isLoading = true;
            }
        }

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

            visibleItemCount= layoutManager.getChildCount();
            totalItemCount= layoutManager.getItemCount();
            firstVisibleItems= layoutManager.findFirstVisibleItemPosition();

            if(isLoading && totalItemCount>previous_total )
            {
                isLoading=false;
                previous_total=totalItemCount;
            }

            if(!isLoading && (totalItemCount-visibleItemCount)<=(firstVisibleItems+count))
            {
                index = index + count;
                getSearches(count,index);
                isLoading = true;

            }
        }
    };


    private void getBloodGroups() {
        service= ApiClient.createService(ApiCall.class,HomeActivity.this);
        Call<BloodGroupModel> call=service.getGroups();
        call.enqueue(new Callback<BloodGroupModel>() {
            @Override
            public void onResponse(Call<BloodGroupModel> call, Response<BloodGroupModel> response) {
                if(response.body() != null && response.body().getStatus() != null && response.body().getStatus()){
                    pDialog.dismiss();
                  Toast.makeText(getApplicationContext(),response.body().getMessage(),Toast.LENGTH_LONG).show();
                    Log.d("Message",response.body().getMessage());

                    listblood = response.body().getData();
                    larray=new ArrayList<>();
                    groupSpin=findViewById(R.id.group_spinner);

                    for(int i=0;i<listblood.size();i++){
                        larray.add(listblood.get(i).getBloodGroupName());
                        Log.d("list",larray.toString());
                    }

                    groupSpin.setAdapter(new ArrayAdapter<String>(HomeActivity.this,android.R.layout.simple_spinner_dropdown_item,larray));                   
                    groupSpin.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            groupId=listblood.get(position).getBloodGroupId();

                        }
                    });

                }else{
                    pDialog.dismiss();
                    Toast.makeText(getApplicationContext(),"Failed",Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<BloodGroupModel> call, Throwable t) {
                pDialog.dismiss();
                Toast.makeText(getApplicationContext(),"Check your Internet Connection!!", Toast.LENGTH_SHORT).show();
                Log.d("Issue",t.getMessage());
            }
        });
    }

    private void getDistrict() {
        service= ApiClient.createService(ApiCall.class,HomeActivity.this);
        Call<DistrictModel> call=service.getdistricts();
        call.enqueue(new Callback<DistrictModel>() {
            @Override
            public void onResponse(Call<DistrictModel> call, Response<DistrictModel> response) {
                if(response.body() != null && response.body().getStatus() != null && response.body().getStatus()){
                  Toast.makeText(getApplicationContext(),response.body().getMessage(),Toast.LENGTH_LONG).show();
                    Log.d("Message",response.body().getMessage());

                    listdistrict=response.body().getData();
                    distSpin=findViewById(R.id.district_spinner);
                    darray=new ArrayList<>();
                    for(int i=0;i<listdistrict.size();i++){
                        disId=listdistrict.get(i).getDistrictId();
                        darray.add(listdistrict.get(i).getDistrict());
                        Log.d("list",darray.toString());
                    }

                    distSpin.setAdapter(new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_spinner_dropdown_item,darray));

                    distSpin.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            Log.d(" selected spinner ", String.valueOf(position));
                            getDistrictId(position);
                        }
                    });
                }
                else{
                Toast.makeText(getApplicationContext(),"Failed",Toast.LENGTH_LONG).show();
                }

            }

            @Override
            public void onFailure(Call<DistrictModel> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "Check your Internet Connection!!", Toast.LENGTH_SHORT).show();
                Log.d("Issue",t.getMessage());

            }
        });
    }
    private void getDistrictId(int position) {
        String district_id="";
        try {

            district_id = listdistrict.get(position).getDistrictId();
            disId = district_id;
            getTaluks(district_id);
            talukSpin.getText().clear();
        }catch (Exception e){
            Log.d("Exception",e.toString());
        }

    }

    private void getTaluks(String district_id) {

        ProgressDialog pDialog=new ProgressDialog(HomeActivity.this);
        pDialog.setMessage("Loading Taluks..");
        pDialog.setCancelable(false);
        pDialog.show();

        tarray = new ArrayList<>();
        service=ApiClient.createService(ApiCall.class,HomeActivity.this);
        Call<TalukModel> call=service.getTaluk(district_id);
        call.enqueue(new Callback<TalukModel>() {
            @Override
            public void onResponse(Call<TalukModel> call, Response<TalukModel> response) {
                if (response.body() != null && response.body().getStatus() != null && response.body().getStatus()) {
                    pDialog.dismiss();

                    Log.d("Message", response.body().getMessage());

                    listtaluk = response.body().getData();
                    talukSpin = findViewById(R.id.taluk_spinner);
                    for (int i = 0; i < listtaluk.size(); i++) {
                        tarray.add(listtaluk.get(i).getTalukName());
                        Log.d("list", tarray.toString());
                    }

                    talukSpin.setAdapter(new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, tarray));
                    talukSpin.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Log.d("BloodGroup ", String.valueOf(position));
                            talukId=listtaluk.get(position).getTalukId();

                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<TalukModel> call, Throwable t) {
                pDialog.dismiss();
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
                Log.d("Issue",t.getMessage());

            }
        });
    }

    private void setRecyclerViewPagination() {
        index=0;
        dataList = new ArrayList<>();
        sadapter=new SearchAdapter(HomeActivity.this,dataList);
        layoutManager = new LinearLayoutManager(HomeActivity.this, LinearLayoutManager.VERTICAL, false);
        recycleList.setNestedScrollingEnabled(false);
        recycleList.setLayoutManager(layoutManager);
        recycleList.setHasFixedSize(true);

        recycleList.setAdapter(sadapter);

        getSearches(count,index);
        recycleList.addOnScrollListener(recycleOnScroll);

    }

    private void getSearches(final int count,final int index) {

        final boolean isFirstPage=index == 0 ? true : false;

        if(isFirstPage)

            progress.setVisibility(View.VISIBLE);

            Call<SearchModel> call = service.getSearchResult(groupId, disId, talukId, count, index);

        call.enqueue(new Callback<SearchModel>() {
            @Override
            public void onResponse(Call<SearchModel> call, Response<SearchModel> response) {
                try {
                    if (response.body() != null && response.body().getStatus() != null && response.body().getStatus()) {
                        text.setVisibility(View.GONE);
                        List<SearchData> data = new ArrayList<>();
                        if (response.body().getData() != null) {
                            data = response.body().getData();
                            if (isFirstPage)
                                dataList.clear();
                                dataList.addAll(data);
                                sadapter.notifyDataSetChanged();
                        }

                        if (data.size() > 0) {
                            isLoading = true;
                        } else {
                            isLoading = false;
                        }

                    }
                        else
                     {
                        isLoading=false;
                    //    recycleList.setVisibility(View.GONE);
                        text.setVisibility(View.VISIBLE);

                    }
                    progress.setVisibility(View.GONE);

                }catch(Exception e){
                    Log.e("Issue","Error"+e.toString());
                    isLoading=false;
                }
            }

            @Override
            public void onFailure(Call<SearchModel> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
                isLoading=false;

            }
        });

            }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_user) {
            Intent i=new Intent(getApplicationContext(),RegisterActivity.class);
            startActivity(i);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            Intent i=new Intent(getApplicationContext(),HomeActivity.class);
            startActivity(i);

        } else if (id == R.id.nav_about) {

        } else if (id == R.id.nav_register) {
            Intent r=new Intent(getApplicationContext(),RegisterActivity.class);
            startActivity(r);

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }}

SearchAdapter.java

public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.ViewHolder> {
    private Context context;
    private List<SearchData> sdata;

    public SearchAdapter(Context context,List<SearchData> sdata){
        this.context=context;
        this.sdata=sdata;
    }


    @NonNull
    @Override
    public SearchAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View view = LayoutInflater.from(context).inflate(R.layout.list_searchresults, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull SearchAdapter.ViewHolder viewHolder, int i) {
        final SearchData sd=sdata.get(i);
        viewHolder.name.setText(sd.getName());
        viewHolder.phone.setText(sd.getPhone());
        viewHolder.email.setText(sd.getEmail());
        viewHolder.dist.setText(sd.getDistrict());
        viewHolder.taluk.setText(sd.getTalukName());
        viewHolder.bgroup.setText(sd.getBloodGroupName());

    }

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



    public class ViewHolder extends RecyclerView.ViewHolder{
        TextView name,phone,dist,taluk,email,bgroup;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            name=itemView.findViewById(R.id.list_names);
            phone=itemView.findViewById(R.id.list_phones);
            dist=itemView.findViewById(R.id.list_districts);
            taluk=itemView.findViewById(R.id.list_taluks);
            email=itemView.findViewById(R.id.list_emails);
            bgroup=itemView.findViewById(R.id.list_groups);
        }
    }}

0 个答案:

没有答案