微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ViewPager2适配器被称为两次

如何解决ViewPager2适配器被称为两次

我从Android Java开发开始,并且在ViewPager2实现上遇到问题。 在我的应用程序上,我有一个ViewPager2,并在上面加上一个具有RecycleView的布局。

问题是,当我将ViewPager2从页面0转到页面1时,适配器执行两次onBindViewHolder,从适配器位置0跳到1并立即从位置1跳到2。(ViewPager2位置保持在1)

当我用Volley DB咨询填充RecycleView时,仅在ViewPAger2适配器完成其工作后(适配器在onBindViewHolder上执行了两次),此操作才开始。因此,只有ViewPager2位置2被填充(两次),ViewPager2页面1保持为空。

因此,我恳请您的帮助避免ViewPAger2更改后,适配器在onBindViewHolder上执行两次。或使Volley在适配器位置从0更改为1并从1更改为2时再次执行其线程。

请帮助我,因为我有5天的时间解决此问题,但未成功。

请参阅我的代码

MY VIEWPAGER2适配器(Adapter_Department)

package br.com.portosaue.portosaueapp;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.linearlayoutmanager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolBox.StringRequest;
import com.android.volley.toolBox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Adapter_Department extends RecyclerView.Adapter<Adapter_Department.UserViewHolder> {

    Context mContext;

    private RecyclerView rcv_products;
    private RecyclerView.Adapter mAdapter;
    private linearlayoutmanager mLayoutManager;
    ViewPager2 vpg_productList;

    List<Department> departmentList;

    String Host_IP;
    String ProductComment;


    public MyAdapter(Context mContext,List<Department> departmentList) {
        this.mContext = mContext;
        this.departmentList = departmentList;
    }



    @NonNull
    @Override
    public UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {

        Host_IP = "192.168.0.100";
        View view = LayoutInflater.from(mContext).inflate(R.layout.products_list,parent,false);
        return new UserViewHolder(view);
    }


    @Override
    public void onBindViewHolder(@NonNull UserViewHolder holder,int position) {
        
        productsList(departmentList.get(position).getName());

    }


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


    public class UserViewHolder extends RecyclerView.ViewHolder {

        public UserViewHolder(@NonNull final View itemView) {
            super(itemView);

            rcv_products = itemView.findViewById(R.id.rcv_Products);
            vpg_productList = ((Activity) mContext).findViewById(R.id.vpg_Products);
        }
    }



    private void productsList(String department){

         //SELECTING URL
        String json_products;

        switch (department) {

            case "Salao":
                json_products = "http://" + Host_IP + "/getSalon.PHP";
                break;
            case "Cozinha":

                json_products = "http://" + Host_IP + "/getKitchen.PHP";
                break;

            case "copa":

                json_products = "http://" + Host_IP + "/getDrink.PHP";
                break;

            case "Churrasqueira":

                json_products = "http://" + Host_IP + "/getBarbecue.PHP";
                break;

            case "Caixa":

                json_products = "http://" + Host_IP + "/getCash.PHP";
                break;
            default:
                json_products = "http://" + Host_IP + "/getProducts";
        }


        //VOLLEY / FETCH / JSONOBJECT
        StringRequest stringRequest = new StringRequest(Request.Method.GET,json_products,new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            //converting the string to json array object
                            JSONArray array = new JSONArray(response);

                            ArrayList<Func_LoadProduct> loadproduct = new ArrayList<Func_LoadProduct>();
                            Func_LoadProduct p;
                            String ImagePath;

                            //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
                                ImagePath = "http://" + Host_IP + "/PS APP Images/" + product.getString("Imagem");

                                p = new Func_LoadProduct(product.getInt("ID"),product.getString("Nome"),product.getDouble("Preco"),ImagePath,"");
                                loadproduct.add(p);
                            }
                            
                            rcv_products=((Activity)mContext).findViewById(R.id.rcv_Products);
                            rcv_products.setHasFixedSize(true);
                            mLayoutManager=new linearlayoutmanager(mContext);
                            mAdapter=new Adapter_Products(loadproduct);

                            rcv_products.setLayoutManager(mLayoutManager);
                            rcv_products.setAdapter(mAdapter);

                        } catch (JSONException e) {
                            e.printstacktrace();
                        }
                    }
                },new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        
        Volley.newRequestQueue(mContext).add(stringRequest);
    }
}

VIEWPAGER2 CLASS(产品)


    package br.com.portosaue.portosaueapp;
    
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;
    
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.appcompat.widget.Toolbar;
    import androidx.viewpager2.widget.ViewPager2;
    
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolBox.StringRequest;
    import com.android.volley.toolBox.Volley;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class Products extends AppCompatActivity {
    
    
        ViewPager2 vpg_products;
        List<Department> departmentList;
        Adapter_Department adapterDepartment;
        String TableNumb;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_products);
    
            vpg_products = findViewById(R.id.vpg_Products);
    
    
            departmentList = new ArrayList<>();
            departmentList.add(new Department("Salon"));
            departmentList.add(new Department("Kitchen"));
            departmentList.add(new Department("Bar"));
    
            adapterDepartment = new Adapter_Department(this,departmentList);
            vpg_products.setAdapter(adapterDepartment);
        }
    
    }

VIEWPAGER2布局(activity_departments.xml)


    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".Products"
        android:orientation="vertical">
    
        <include
            android:id="@+id/tbr_toobar"
            layout = "@layout/toolbar"/>
    
    
        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/vpg_Products"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_below="@+id/tbr_toobar"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tbr_toobar"
            app:layout_constraintVertical_bias="1.0" />
    
    
    </androidx.constraintlayout.widget.ConstraintLayout>

RECYCLEVIEW适配器(Adapter_Products)


    package br.com.portosaue.portosaueapp;
    
    import android.content.Context;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    
    import com.squareup.picasso.Picasso;
    
    import java.util.ArrayList;
    
    
    
    public class Adapter_Products extends  RecyclerView.Adapter<Adapter_Products.MyViewHolder>{
    
    
        private ArrayList<Func_LoadProduct> mProductList;
    
        public static class MyViewHolder extends RecyclerView.ViewHolder {
            public ImageView img_Productimage;
            public TextView txv_ProductName;
            public TextView txv_ProductPrice;
            public TextView txv_ProductID;
    
    
            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
    
                img_Productimage = itemView.findViewById(R.id.imv_Productimage);
                txv_ProductName = itemView.findViewById(R.id.txv_ProductName);
                txv_ProductPrice = itemView.findViewById(R.id.txv_ProductPrice);
                txv_ProductID = itemView.findViewById(R.id.txv_ProcutID);
    
            }
        }
    
        public Adapter_Products( ArrayList<Func_LoadProduct> productList){
    
            this.mProductList=productList;
        }
    
    
    
    
        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
    
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_line,false);
            MyViewHolder evh = new MyViewHolder(v);
    
            return evh;
        }
    
    
        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder,int position) {
    
    
            Func_LoadProduct currentItem = mProductList.get(position);
    
            Picasso.get().load(mProductList.get(position).getProductimageName()).into(holder.img_Productimage);
    
            holder.txv_ProductName.setText(currentItem.getProductName());
            holder.txv_ProductPrice.setText("R$ " + Double.toString(currentItem.getProductPrice()));
            holder.txv_ProductID.setText("ID: " + Integer.toString(currentItem.getProductID()));
    
        }
    
        @Override
        public int getItemCount() {
    
            return mProductList.size();
        }
    
    }

RECYCLEVIEW布局(product_list.xml)


    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
    
    
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rcv_Products"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="0dp"
            android:layout_marginTop="0dp" />
    
    </RelativeLayout>

ITEMS类别(Func_LoadProduct)


    package br.com.portosaue.portosaueapp;
    
    
    public class Func_LoadProduct {
    
        private int ProductID;
        private String ProductName;
        private double ProductPrice;
        private String ProductimageName;
        private String ProductComment;
    
    
    
    
        public Func_LoadProduct(int productID,String productName,double productPrice,String productimageName,String productComment){
    
            this.ProductID = productID;
            this.ProductName = productName;
            this.ProductPrice = productPrice;
            this.ProductimageName = productimageName;
            this.ProductComment = productComment;
        }
    
        //SET
        public void setProductID(int productID) {
            this.ProductID = productID;
        }
    
        public void setProductName(String productName) {
            this.ProductName = productName;
        }
    
        public void setProductPrice(double productPrice) {
            this.ProductPrice = productPrice;
        }
    
        public void setProductimageName(String productimageName) { this.ProductimageName = productimageName; }
    
        public void setProductComment(String productComment) { this.ProductComment = productComment; }
    
    
        //GET
        public int getProductID() {
            return this.ProductID;
        }
    
        public String getProductName() {
            return this.ProductName;
        }
    
        public double getProductPrice() {
            return this.ProductPrice;
        }
    
        public String getProductimageName() { return this.ProductimageName; }
    
        public String getProductComment() { return this.ProductComment;  }
    }

项目布局(product_line.xml)

<?xml version="1.0" encoding="utf-8"?>

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:cardCornerRadius="4dp"
    android:layout_marginTop="2dp"
    android:layout_marginBottom="2dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="4dp">


        <ImageView
            android:id="@+id/imv_Productimage"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:padding="2dp"
            android:scaleType="fitXY"
            tools:srcCompat="@tools:sample/avatars"/>


        <TextView
            android:id="@+id/txv_ProductName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="64dp"
            android:layout_marginTop="2dp"
            android:textColor="@android:color/black"
            android:textSize="20sp"
            android:layout_weight="10"
            android:text="Produto"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"/>


        <TextView
            android:id="@+id/txv_ProductPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignStart="@+id/txv_ProductName"
            android:layout_alignParentTop="true"
            android:layout_marginStart="2dp"
            android:layout_marginTop="31dp"
            android:layout_weight="3"
            android:text="Valor"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/txv_ProcutID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/txv_ProductPrice"
            android:layout_alignParentStart="true"
            android:layout_marginStart="347dp"
            android:layout_marginBottom="0dp"
            android:layout_weight="1"
            android:text="ID"
            android:textSize="15sp" />


    </RelativeLayout>

</androidx.cardview.widget.CardView>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。