Java 在动态数据分页中,Recyclerview滚动条自动向上(顶部)

Java 在动态数据分页中,Recyclerview滚动条自动向上(顶部),java,android,android-recyclerview,Java,Android,Android Recyclerview,我正在使用分页样式从我的recyclerView中的本地服务器获取数据,即在完成第一页项目后获取下一页。我走了这么远,但我遇到了一个问题,自动滚动到顶部,而它到达下一页等。 这是片段的代码 public class AVehicleFragment extends Fragment { Button btnsearch; RequestQueue requestQueue; StringRequest stringRequest; List<Vehicleinfo> vehiclei

我正在使用分页样式从我的recyclerView中的本地服务器获取数据,即在完成第一页项目后获取下一页。我走了这么远,但我遇到了一个问题,自动滚动到顶部,而它到达下一页等。 这是片段的代码

public class AVehicleFragment extends Fragment {
Button btnsearch;
RequestQueue requestQueue;
StringRequest stringRequest;
List<Vehicleinfo> vehicleinfos;
RecyclerView recyclerView;
VehiclelistAdapter vehiclelistAdapter;
LinearLayoutManager layoutManager;
int PAGE_SIZE = 20;
int PAGE_NUMBE= 1;
int currentitem,totalitem,scrolleditem;
//RecyclerView.LayoutManager layoutManager;
boolean isScrolling = false;
ProgressBar progressBar;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_avehicle, container, false);
    btnsearch = view.findViewById(R.id.btnsearch);
    progressBar = view.findViewById(R.id.progressbar);
    vehicleinfos = new ArrayList<>();
    recyclerView = view.findViewById(R.id.rvvehilelist);
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                isScrolling = true;
                recyclerView.scrollToPosition(scrolleditem);
                Log.d(TAG, "onScrollStateChanged: ");
            }


        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            currentitem = layoutManager.getChildCount();
            scrolleditem = layoutManager.findFirstVisibleItemPosition();
            totalitem = layoutManager.getItemCount();
            if (isScrolling &&(currentitem + scrolleditem==totalitem)){
                isScrolling=false;
                fetchData();
              //  recyclerView.scrollToPosition(scrolleditem);
                Log.d(TAG, "onScrollStateChanged: ");
            }


        }
    });

    layoutManager = new LinearLayoutManager(getContext());
    readInitialvehicle(PAGE_SIZE,PAGE_NUMBE);
    recyclerView.scrollToPosition(scrolleditem);
    return view;
}

public void readInitialvehicle(int pagesize, int pagenum){

    requestQueue = Volley.newRequestQueue(getContext());
    String url = MConstant.URL+MConstant.VEHICLEPAGESIZE+pagesize+MConstant.VEHICLEPAGENUMBER+pagenum;

    stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONArray jsonArray = new JSONArray(response);
                for (int i =0;i<jsonArray.length();i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String vehiclenum = jsonObject.getString("VehicleNumber");
                    String owner = jsonObject.getString("Owner");
                    String driver = jsonObject.getString("Driver");
                    String vehicletype = jsonObject.getString("VehicleType");
                    String registrationfee = jsonObject.getString("RegistrationFee");
                    String vehicleengine = jsonObject.getString("EngineType");
                    String balance = jsonObject.getString("LatestBalance");
                    String vehicleid = jsonObject.getString("VehicleId");

                    Vehicleinfo vehicleinfo = new Vehicleinfo(owner,driver,vehiclenum,vehicletype,registrationfee,vehicleengine,balance,vehicleid);
                    vehicleinfos.add(vehicleinfo);

                }
                vehiclelistAdapter = new VehiclelistAdapter(vehicleinfos);
                recyclerView.setLayoutManager(layoutManager);
                recyclerView.setAdapter(vehiclelistAdapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "onErrorResponse: ");

        }
    });


    requestQueue.add(stringRequest);

}

public void fetchData(){
    progressBar.setVisibility(View.VISIBLE);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            PAGE_SIZE= PAGE_SIZE+20;
            PAGE_NUMBE=PAGE_NUMBE+1;
            readInitialvehicle(PAGE_SIZE,PAGE_NUMBE);
            progressBar.setVisibility(View.GONE);


        }
    },3000);
}
public类AVehicleFragment扩展片段{
按钮搜索;
请求队列请求队列;
StringRequest-StringRequest;
列出车辆信息;
回收视图回收视图;
VehiclelistAdapter VehiclelistAdapter;
直线布局经理布局经理;
int PAGE_SIZE=20;
整版页码=1;
int currentitem、totalitem、scrolleditem;
//RecyclerView.LayoutManager LayoutManager;
布尔isScrolling=false;
ProgressBar ProgressBar;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//为该碎片膨胀布局
视图=充气机。充气(R.layout.fragment\u车辆,容器,假);
btnsearch=view.findviewbyd(R.id.btnsearch);
progressBar=view.findViewById(R.id.progressBar);
VehicleInfo=新的ArrayList();
recyclerView=view.findViewById(R.id.rvveHilleList);
recyclerView.addOnScrollListener(新的recyclerView.OnScrollListener(){
@凌驾
CrollStateChanged上的公共void(@NonNull RecyclerView RecyclerView,int newState){
super.onScrollStateChanged(recyclerView、newState);
if(newState==AbsListView.OnScrollListener.SCROLL\u STATE\u IDLE){
isScrolling=true;
recyclerView.scrollToPosition(scrolleditem);
Log.d(标记“onScrollStateChanged:”);
}
}
@凌驾
已克隆的公共void(@NonNull RecyclerView RecyclerView,int-dx,int-dy){
super.onScrolled(recyclerView、dx、dy);
currentitem=layoutManager.getChildCount();
scrolleditem=layoutManager.findFirstVisibleItemPosition();
totalitem=layoutManager.getItemCount();
if(isScrolling&&(currentitem+scrolleditem==totalitem)){
IsCrolling=假;
fetchData();
//recyclerView.scrollToPosition(scrolleditem);
Log.d(标记“onScrollStateChanged:”);
}
}
});
layoutManager=新的LinearLayoutManager(getContext());
readInitialvehicle(页码大小、页码);
recyclerView.scrollToPosition(scrolleditem);
返回视图;
}
公共无效readInitialvehicle(int pagesize,int pagenum){
requestQueue=Volley.newRequestQueue(getContext());
字符串url=MConstant.url+MConstant.VEHICLEPAGESIZE+pagesize+MConstant.VEHICLEPAGENUMBER+pagenum;
stringRequest=newStringRequest(Request.Method.GET,url,new Response.Listener()){
@凌驾
公共void onResponse(字符串响应){
试一试{
JSONArray JSONArray=新JSONArray(响应);

对于(int i=0;ii think
scrolleditem=layoutManager.findFirstVisibleItemPosition())
这里,接收0零意味着一直滚动它,提供firstvisibleitemposition=1。这就是为什么添加新数据时,它会消失的原因up@Ashish它不会每次都给零。当项目在1时,它会给零。我忘记将接收0更改为1。请参阅我更新的滚动,它提供FrestVistiBuffItPo位置=1。考虑使用分页L。library@DmitriiLeonov谢谢您的考虑,但这里我不使用MVVMi think
scrolleditem=layoutManager.findFirstVisibleItemPosition()
这里,接收0零意味着一直滚动它,提供firstvisibleitemposition=1。这就是为什么添加新数据时,它会消失的原因up@Ashish它不会每次都给零。当项目在1时,它会给零。我忘记将接收0更改为1。请参阅我更新的滚动,它提供FrestVistiBuffItPo位置=1。考虑使用分页L。library@dmitrileonov谢谢您的考虑,但这里我不使用MVVM
public class VehiclelistAdapter extends RecyclerView.Adapter<VehiclelistAdapter.ViewHolder> {
List<Vehicleinfo> vehicleinfos;

public VehiclelistAdapter(List<Vehicleinfo> vehicleinfos) {
    this.vehicleinfos = vehicleinfos;
}

@NonNull
@Override
public VehiclelistAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_vehiclelist_fragment,parent,false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull VehiclelistAdapter.ViewHolder holder, final int position) {
    final Vehicleinfo vehicleinfo = vehicleinfos.get(position);
    String vehiclenum = vehicleinfo.getVehiclenum();
    String owner = vehicleinfo.getOwner();
    String driver = vehicleinfo.getDriver();
    String sn = String.valueOf(position+1);
    holder.tvvehiclenum.setText(vehiclenum);
    holder.tvowner.setText(owner);
    holder.tvdriver.setText(driver);

    holder.tvsn.setText(sn);
    if (position%2 ==1){
        holder.itemView.setBackgroundColor(Color.parseColor("#D3B3E2"));
    }
    else {
        holder.itemView.setBackgroundColor(Color.parseColor("#FFFFFF"));
    }

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Bundle bundle = new Bundle();
            String vehicletype = vehicleinfo.getVehicletype();
            String registrationfee = vehicleinfo.getRegistrationfee();
            String enginetype = vehicleinfo.getVehicleengine();
            String balance = vehicleinfo.getBalance();
            String vehiclenumber = vehicleinfo.getVehiclenum();
            String vehicleid = vehicleinfo.getVehicleid();


            bundle.putString("vehicletype",vehicletype);
            bundle.putString("registrationfee",registrationfee);
            bundle.putString("enginetype",enginetype);
            bundle.putString("balance",balance);
            bundle.putString("vehiclenumber",vehiclenumber);
            bundle.putString("vehicleid",vehicleid);

            AVehicledetailFragment vehicledetailFragment = new AVehicledetailFragment();
            vehicledetailFragment.setArguments(bundle);

            AppCompatActivity appCompatActivity = (AppCompatActivity) v.getContext();
            appCompatActivity.getSupportFragmentManager().beginTransaction().replace(R.id.fcontainer,vehicledetailFragment).addToBackStack(null).commit();

        }
    });

}

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

public class ViewHolder extends RecyclerView.ViewHolder {
    TextView tvsn,tvvehiclenum,tvowner,tvdriver;
    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        tvsn = itemView.findViewById(R.id.tvsn);
        tvdriver = itemView.findViewById(R.id.tvdrivername);
        tvowner = itemView.findViewById(R.id.tvownername);
        tvvehiclenum = itemView.findViewById(R.id.tvvehiclenum);
    }
}