Use Single Fragment in Multiple tabs of ViewPager

前端 未结 3 1469
粉色の甜心
粉色の甜心 2020-12-16 08:39

I am using ViewPager to slide left and right, I have also added the tabs, The number of tabs is depends on the server data, So, I cannot make the number of tabs as Fixed. To

3条回答
  •  感动是毒
    2020-12-16 09:03

    In PagerAdapter edit as below, it might help:

    @Override
    public Fragment getItem(int position) {
       /* ProductFragment pf = ProductFragment.newInstance(data.get(position),position);
        return pf;*/
    
        return ProductFragment.newInstance(data.get(position),position);
    }
    

    And in your Fragment make changes as below:

    public class ProductFragment extends Fragment {
    private static final String ARG_PRODUCTS = "PRODS";
    private static List allProducts;
    int position = 0;
    RecyclerView prodList;
    ProductAdapter productAdapter=null;
    
    
    public static ProductFragment newInstance(List products,int position) {        
    ProductFragment fragment = new ProductFragment();
    Bundle args = new Bundle();
    args.putParcelableArrayList(ARG_PRODUCTS, (ArrayList) products);
    args.putInt("KEY_POSITION",position);
    args.putInt("KEY_ID",id);
    fragment.setArguments(args);
    return fragment;
    }
    
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
      if(isVisibleToUser){
          productAdapter.notifyDataSetChanged();
        }
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //if(isVisibleToUser){
        if (getArguments() != null) {
            allProducts = getArguments().getParcelableArrayList(ARG_PRODUCTS);
            this.position = getArguments().getInt("KEY_POSITION");
        }
    

    // } }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_product, container, false);
    prodList = (RecyclerView) view.findViewById(R.id.product_list);
    prodList.setLayoutManager(new LinearLayoutManager(getActivity()));
    productAdapter= new ProductAdapter(getActivity(), allProducts)
    prodList.setAdapter(productAdapter);
            return view;
       }
    }
    

提交回复
热议问题