当前位置: 首页 > 面试题库 >

recyclerview滚动并保持在旧位置不要转到顶部

岳枫
2023-03-14
问题内容

我的问题是当我在回收视图中滚动数据时,所以加载了新数据,但问题是当新数据加载时,回收视图从第一个产品开始,

我需要保持旧的位置,只滚动新数据,而不滚动所有旧数据

目前,我正在添加文件adeptoer文件和主文件的完整代码,

public class adepter extends RecyclerView.Adapter<adepter.viewholder> {

    private Context mCtx;
    private List<Product> productList;
        public adepter(Context mCtx, List<Product> productList) {
            this.mCtx = mCtx;
            this.productList = productList;
        }

    @NonNull
    @Override
    public adepter.viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater=LayoutInflater.from(mCtx);
        View v =inflater.inflate(R.layout.product_list, parent, false);
        final viewholder vh = new viewholder(v);
        vh.itemView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Product product = productList.get(vh.getAdapterPosition());
                //do the page opening here
                Intent intent = new Intent(mCtx, product_info.class);
                intent.putExtra("id",product.getId());

                mCtx.startActivity(intent);

            }
        });
        return vh;

    }

    @Override
    public void onBindViewHolder(@NonNull adepter.viewholder holder, int position) {
        Product product = productList.get(position);
        //loading the image
        Glide.with(mCtx)
                .load(product.getImage())
                .into(holder.imageView);
        holder.textViewTitle.setText(product.getTitle());
        holder.textViewShortDesc.setText(product.getShortdesc());
        holder.textViewtype.setText(String.valueOf(product.getType()));
        holder.textViewPrice.setText("Rs: "+String.valueOf(product.getPrice()));
    }

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





    public class viewholder extends RecyclerView.ViewHolder{
        TextView textViewTitle, textViewShortDesc, textViewtype, textViewPrice;
        ImageView imageView;
        public viewholder(@NonNull View itemView) {
            super(itemView);
            textViewTitle = itemView.findViewById(R.id.textViewTitle);
            textViewShortDesc = itemView.findViewById(R.id.textViewShortDesc);
            textViewtype = itemView.findViewById(R.id.textViewRating);
            textViewPrice = itemView.findViewById(R.id.textViewPrice);
            imageView = itemView.findViewById(R.id.imageView);
        }
    }
}



public class home extends AppCompatActivity {

  //a list to store all the products
    List<Product> productList;
    //the recyclerview
    RecyclerView recyclerView;
    ProgressBar Pbar;
    GridLayoutManager manager;
    int token = 1;
  Boolean isScrolling = false;
    int currentItems, totalItems, scrollOutItems;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        Pbar = findViewById(R.id.progressBar1);
        //getting the recyclerview from xml
        recyclerView = findViewById(R.id.recylcerView);
        recyclerView.setHasFixedSize(true);
         manager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(manager);

        //initializing the productlist
        productList = new ArrayList<>();





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

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                currentItems = manager.getChildCount();
                totalItems = manager.getItemCount();
                scrollOutItems = manager.findFirstVisibleItemPosition();

                if(isScrolling && (currentItems + scrollOutItems == totalItems))
                {
                    isScrolling = false;
                    token++;
                    getData();
                }
            }
        });
        getData();


    }





    private void   getData(){
         String url = "https://shop.com/index.php";

         url = url+ "&pg="+ String.valueOf(token);

        Pbar.setVisibility(View.VISIBLE);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //   Toast.makeText(getApplicationContext(),"volly ok ",Toast.LENGTH_LONG).show();
                        try {
                            //converting the string to json array object
                            JSONArray array = new JSONArray(response);
                            //traversing through all the object
                            for (int i = 0; i < array.length(); i++) {
                                //getting product object from json array
                                JSONObject product = array.getJSONObject(i);
                                //adding the product to product list
                                productList.add(new Product(
                                        product.getInt("id"),
                                        product.getString("title"),
                                        product.getString("shortdesc"),
                                        product.getString("type"),
                                        product.getString("price"),
                                        product.getString("image")
                                ));
                            }
                            //  Toast.makeText(getApplicationContext(),productList+ "volly ok ",Toast.LENGTH_LONG).show();

                          adepter a = new adepter(home.this, productList);
                            recyclerView.setAdapter(a);

                            Pbar.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Server Error" ,Toast.LENGTH_LONG).show();
                    }
                });

        //adding our stringrequest to queue
        Volley.newRequestQueue(this).add(stringRequest);
    }

}

问题答案:

试试这个:

public class home extends AppCompatActivity {

  //a list to store all the products
    List<Product> productList;
    //the recyclerview
    RecyclerView recyclerView;
    adepter a;
    ProgressBar Pbar;
    GridLayoutManager manager;
    int token = 1;
  Boolean isScrolling = false;
    int currentItems, totalItems, scrollOutItems;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        Pbar = findViewById(R.id.progressBar1);
        //getting the recyclerview from xml
        recyclerView = findViewById(R.id.recylcerView);
        recyclerView.setHasFixedSize(true);
         manager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(manager);

        //initializing the productlist
        productList = new ArrayList<>();


 a = new adepter(home.this, productList);
                recyclerView.setAdapter(a);


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

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                currentItems = manager.getChildCount();
                totalItems = manager.getItemCount();
                scrollOutItems = manager.findFirstVisibleItemPosition();

                if(isScrolling && (currentItems + scrollOutItems == totalItems))
                {
                    isScrolling = false;
                    token++;
                    getData();
                }
            }
        });
        getData();


    }





    private void   getData(){
         String url = "https://shop.com/index.php";

         url = url+ "&pg="+ String.valueOf(token);

        Pbar.setVisibility(View.VISIBLE);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //   Toast.makeText(getApplicationContext(),"volly ok ",Toast.LENGTH_LONG).show();
                        try {
                            //converting the string to json array object
                            JSONArray array = new JSONArray(response);
                            //traversing through all the object
                            for (int i = 0; i < array.length(); i++) {
                                //getting product object from json array
                                JSONObject product = array.getJSONObject(i);
                                //adding the product to product list
                                productList.add(new Product(
                                        product.getInt("id"),
                                        product.getString("title"),
                                        product.getString("shortdesc"),
                                        product.getString("type"),
                                        product.getString("price"),
                                        product.getString("image")
                                ));
                            }
                            a.notifyDataSetChanged();



                            Pbar.setVisibility(View.GONE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Server Error" ,Toast.LENGTH_LONG).show();
                    }
                });

        //adding our stringrequest to queue
        Volley.newRequestQueue(this).add(stringRequest);
    }

}


 类似资料:
  • 我有一个非常标准的,带有垂直。我一直在顶部插入新项目,并调用 < 我希望列表保持滚动到顶部;总是显示第0个位置。 从我的需求的角度来看,< code>LayoutManager根据项目的数量表现不同。 虽然所有项目都适合屏幕,但它的外观和行为与我预期的一样:新项目总是出现在顶部,并移动其下的所有项目。 但是,一旦项目数超过RecyclerView的界限,新项目就会添加到当前可见项目的上方,但可见项

  • 我正在做一个西班牙新闻应用程序,看这里: 这个应用程序的问题是,每当任何用户点击like、play audio或translate按钮时,recyclerView就会跳到顶部。 > 数据以片段形式从Firebase实时数据库中获取。请帮帮忙。 @override public View onCreateView(LayoutInfluater Influater,ViewGroup contain

  • 如何刷新显示在中的数据(在其适配器上调用),并确保滚动位置被重置到它原来的位置? 如果是良好的ol'则只需检索,检查其,然后使用相同的精确数据调用。 在的情况下,这似乎是不可能的。 我想我应该使用它的,它确实提供了,但是检索位置和偏移量的正确方法是什么? 和? 还是有更优雅的方法来完成这项工作?

  • 问题内容: 这是我的onCreate,它处理适配器,LinearLayoutManager等。我尝试了每个选项以尝试将其滚动到顶部,但不能。我什至尝试创建自己的自定义LinearLayoutManager。 问题答案: 您尝试过还是? RecyclerView不会在其中实现任何滚动逻辑,而是更加具体,它会根据实现的布局转到特定的索引,在您的情况下是线性的。

  • 问题内容: 有人可以告诉我我在做什么错吗?我需要在一段时间后刷新页面,但是它会刷新到页面顶部,我需要不更改页面位置!所以这是我现在无法使用的,是meta标签吗?这是我所没有的仍然不刷新必须做错了什么吗? 这是我本来的… 阅读了一些初始答案后,我将其更改为… 问题答案: 更新 您可以使用下面提到的方法代替下面的强制技巧。 将HTML替换为:

  • 本文向大家介绍切换到新路由时,页面要滚动到顶部或保持原先的滚动位置怎么做呢?相关面试题,主要包含被问及切换到新路由时,页面要滚动到顶部或保持原先的滚动位置怎么做呢?时的应答技巧和注意事项,需要的朋友参考一下 滚动到顶部:在new Router()的时候,配置 scrollBehavior(to, from, savedPosition) { return { x: 0, y: 0 } }