Мои данные ViewPager FragmentView и макет исчезают после возвращения из фрагмента - PullRequest
0 голосов
/ 14 апреля 2020

Я получаю объект от modelView, как вы, ребята, видите. Каждая вещь прекрасно работает, кроме моего фрагмента видового пейджера, когда я впервые прихожу к своему фрагменту пейджера, он показывает данные, когда я go проходит вперед, а затем возвращаюсь назад, он пропадает мои данные и моя структура макета. Мои viewModel имеют данные всегда имеют данные, но мои recyclerview не показывают их.

BrandFragment - это базовый фрагмент с видовым пейджером.

BrandFragment:

public class BrandFragment extends Fragment {


@BindView(R.id.brandtablayout)
TabLayout brandtablayout;
@BindView(R.id.brandpager)
ViewPager brandpager;
@BindView(R.id.backgroundImage)
ImageView backgroundImage;
@BindView(R.id.brandIcon)
CircleImageView brandIcon;
@BindView(R.id.brandName)
TextView brandName;
@BindView(R.id.brandTagLine)
TextView brandTagLine;
@BindView(R.id.brandRatingBar)
RatingBar brandRatingBar;

@BindView(R.id.noInternet)
ImageView noInternet;

private Brand brand;
int chipId;
private KProgressHUD mProgressBar;
private ShareViewModel shareViewModel;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_brand, container, false);
    brandpager = view.findViewById(R.id.brandpager);
    brandtablayout = view.findViewById(R.id.brandtablayout);

    backgroundImage = view.findViewById(R.id.backgroundImage);
    brandIcon = view.findViewById(R.id.brandIcon);
    brandName = view.findViewById(R.id.brandName);
    brandTagLine= view.findViewById(R.id.brandTagLine);
    brandRatingBar = view.findViewById(R.id.brandRatingBar);
    noInternet = view.findViewById(R.id.noInternet);


    brandtablayout.addTab(brandtablayout.newTab().setText("Product"));
    brandtablayout.addTab(brandtablayout.newTab().setText("Profile"));

    brandtablayout.setTabGravity(TabLayout.GRAVITY_FILL);

    BrandProfileViewPagerAdapter brandProfileAdapter = new BrandProfileViewPagerAdapter(getFragmentManager(), brandtablayout.getTabCount());
    brandpager.setAdapter(brandProfileAdapter);
    brandtablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            brandpager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });


    progressbar("Getting Brand Detail","Please wait...");




    return view;
}

private void getBrandDetails() {
    WebServiceFactory.getInstance().getBrandDetails(chipId).enqueue(new Callback<Brand>() {
        @Override
        public void onResponse(Call<Brand> call, Response<Brand> response) {
            if (response.body().getFlag() == 1) {
                brand = response.body();
                shareViewModel.setBrandProductsMutableLiveData(brand.getBrandProducts());
                shareViewModel.setBrandSpecificationsMutableLiveData(brand.getBrandSpecifications());
                brandProfileDetails();
                mProgressBar.dismiss();
            }else {
                mProgressBar.dismiss();
            }
        }

        @Override
        public void onFailure(Call<Brand> call, Throwable t) {
            mProgressBar.dismiss();
        }
    });


}

private void brandProfileDetails(){
    if (brand.getBrandSpecifications() != null){
        brandRatingBar.setRating(brand.getBrandSpecifications().getBrandRates());
        brandName.setText(brand.getBrandSpecifications().getBrandName());
        Picasso.get().load(AppConstants.imagePath(brand.getBrandSpecifications().getBrandBg())).into(backgroundImage);
        brandTagLine.setText(brand.getBrandSpecifications().getBrandSlogan());
        Picasso.get().load(AppConstants.imagePath(brand.getBrandSpecifications().getBrandIcon())).into(brandIcon);
    }

    mProgressBar.dismiss();

}

    @Override
    public void onViewCreated (@NonNull View view, @Nullable Bundle savedInstanceState){
    super.onViewCreated(view, savedInstanceState);

        shareViewModel = ViewModelProviders.of((FragmentActivity) requireActivity()).get(ShareViewModel.class);
        shareViewModel.getChipId().observe(getViewLifecycleOwner(), new Observer<Integer>() {
            @Override
            public void onChanged(Integer id) {
                chipId =id;

                if (InternetConnection.checkConnection(getContext())) {
                    // Internet Available...
                    noInternet.setVisibility(View.GONE);
                    getBrandDetails();
                } else {
                    noInternet.setVisibility(View.VISIBLE);
                    mProgressBar.dismiss();
                    Toast.makeText(getContext(), "Check your internet Connection", Toast.LENGTH_SHORT).show();
                    // Internet Not Available...
                }

            }
        });
    }



private void progressbar(String title, String detail){
    mProgressBar = KProgressHUD.create(getContext())
            .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setLabel(title)
            .setDetailsLabel(detail)
            .setCancellable(false)
            .setAnimationSpeed(2)
            .setDimAmount(0.5f)
            .show();
}


}

BrandProductFragment:

public class BrandProductFragment extends Fragment implements RecyclerviewOnClickInterface, CategoryRecyclerviewInterface, ChipsInterface, MyButtonClickListener {


int tabCount;
@BindView(R.id.brandPopularProduct)
TextView brandPopularProduct;
@BindView(R.id.brandNewProduct)
TextView brnadNewProduct;
@BindView(R.id.brandHighestProduct)
TextView brandHighestProduct;
@BindView(R.id.brandLowestProduct)
TextView brandLowestProduct;
@BindView(R.id.brandProductRecyclerview)
RecyclerView brandProductRecyclerview;
BrandProfilePopularAdapter brandProfilePopularAdapter;
BrandNewReleaseAdapter brandNewReleaseAdapter;
BrandProductHighestAdapter brandProductHighestAdapter;
BrandLowestAdapter brandLowestAdapter;
BrandProducts brandProductData;

ShareViewModel shareViewModel;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_brand_product, container, false);

    tabCount = 0;




    brandPopularProduct = view.findViewById(R.id.brandPopularProduct);
    brnadNewProduct = view.findViewById(R.id.brandNewProduct);
    brandHighestProduct = view.findViewById(R.id.brandHighestProduct);
    brandLowestProduct = view.findViewById(R.id.brandLowestProduct);
    brandProductRecyclerview = view.findViewById(R.id.brandProductRecyclerview);


    buttonOnClick();

    return view;
}

private void buttonOnClick() {

    brandPopularProduct.setOnClickListener(v -> {
        tabCount = 1;
        tabSelector();
        if (brandProductData != null) {
            getBrandProductPopular(brandProductData);
        }

    });
    brnadNewProduct.setOnClickListener(v -> {
        tabCount = 2;
        tabSelector();

        if (brandProductData != null) {
            getBrandProductNewRelease();
        }

    });
    brandHighestProduct.setOnClickListener(v -> {
        tabCount = 3;
        tabSelector();
        if (brandProductData != null) {
            getBrandProductHighest();
        }

    });
    brandLowestProduct.setOnClickListener(v -> {
        tabCount = 4;
        tabSelector();
        if (brandProductData != null) {
            getBrandProductLowest();
        }

    });


}

private void tabSelector() {
    if (tabCount == 1) {
        brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
        brandPopularProduct.setTextSize(20);
        brnadNewProduct.setTextSize(18);
        brandLowestProduct.setTextSize(18);
        brandHighestProduct.setTextSize(18);
        brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
        brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
        brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));

    } else if (tabCount == 2) {
        brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
        brandPopularProduct.setTextSize(18);
        brnadNewProduct.setTextSize(20);
        brandLowestProduct.setTextSize(18);
        brandHighestProduct.setTextSize(18);
        brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
        brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
        brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));


    } else if (tabCount == 3) {
        brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
        brandPopularProduct.setTextSize(18);
        brnadNewProduct.setTextSize(18);
        brandLowestProduct.setTextSize(18);
        brandHighestProduct.setTextSize(20);
        brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
        brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
        brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));

    } else if (tabCount == 4) {
        brandLowestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor));
        brandPopularProduct.setTextSize(18);
        brnadNewProduct.setTextSize(18);
        brandLowestProduct.setTextSize(20);
        brandHighestProduct.setTextSize(18);
        brnadNewProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
        brandHighestProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));
        brandPopularProduct.setTextColor(ContextCompat.getColor(getContext(), R.color.fontColor2));

    }

}

private void getBrandProductPopular(BrandProducts brandProductData) {
    if (brandProductData.getPOPULARPRODUCTS() != null){
        brandProfilePopularAdapter = new BrandProfilePopularAdapter(getContext(), brandProductData.getPOPULARPRODUCTS(), this);
        GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
        brandProductRecyclerview.setLayoutManager(mLayoutManager);
        brandProductRecyclerview.setAdapter(brandProfilePopularAdapter);
        recyclerviewAnimation(brandProductRecyclerview);
    }

}

private void getBrandProductNewRelease() {
    if ( brandProductData.getNEWRELEASEPRODUCTS() != null){
        brandNewReleaseAdapter = new BrandNewReleaseAdapter(getContext(), brandProductData.getNEWRELEASEPRODUCTS(), this);
        GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
        brandProductRecyclerview.setLayoutManager(mLayoutManager);
        brandProductRecyclerview.setAdapter(brandNewReleaseAdapter);
        recyclerviewAnimation(brandProductRecyclerview);
    }

}


private void getBrandProductHighest() {
    if (brandProductData.getHIGHESTPRODUCTS() != null){
        brandProductHighestAdapter = new BrandProductHighestAdapter(getContext(), brandProductData.getHIGHESTPRODUCTS(), this);
        GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
        brandProductRecyclerview.setLayoutManager(mLayoutManager);
        brandProductRecyclerview.setAdapter(brandProductHighestAdapter);
        recyclerviewAnimation(brandProductRecyclerview);
    }

}

private void getBrandProductLowest() {
    if ( brandProductData.getLOWESTPRODUCTS() != null){
        brandLowestAdapter = new BrandLowestAdapter(getContext(), brandProductData.getLOWESTPRODUCTS(), this);
        GridLayoutManager mLayoutManager = new GridLayoutManager(getContext(), 2);
        brandProductRecyclerview.setLayoutManager(mLayoutManager);
        brandProductRecyclerview.setAdapter(brandLowestAdapter);
        recyclerviewAnimation(brandProductRecyclerview);
    }

}


@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    shareViewModel = ViewModelProviders.of((FragmentActivity) getContext()).get(ShareViewModel.class);
    shareViewModel.getBrandProduct().observe(getViewLifecycleOwner(), new Observer<BrandProducts>() {
        @Override
        public void onChanged(BrandProducts brandProducts) {
            Log.e("getBrands", brandProducts.toString());
            brandProductData = brandProducts;

            getBrandProductPopular(brandProductData);

        }
    });

}

private void recyclerviewAnimation(RecyclerView recyclerView) {
    Context context = recyclerView.getContext();
    LayoutAnimationController layoutAnimationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down);
    recyclerView.setLayoutAnimation(layoutAnimationController);
    recyclerView.getAdapter().notifyDataSetChanged();
    recyclerView.scheduleLayoutAnimation();
}

int productId;

@Override
public void onItemClick(int position) {
    shareViewModel.setProductIdMutable(brandProductData.getPOPULARPRODUCTS().get(position).getProductId());
    fragmentTransaction();
}


@Override
public void onItemClickCategory(int position) {
    shareViewModel.setProductIdMutable(brandProductData.getNEWRELEASEPRODUCTS().get(position).getProductId());
    fragmentTransaction();
}

@Override
public void onChipItemClick(int position) {
    shareViewModel.setProductIdMutable(brandProductData.getHIGHESTPRODUCTS().get(position).getProductId());
    fragmentTransaction();
}

@Override
public void onclick(int position) {

    shareViewModel.setProductIdMutable(brandProductData.getLOWESTPRODUCTS().get(position).getProductId());
    fragmentTransaction();

}


private void fragmentTransaction() {
    Bundle bundle = new Bundle();
    bundle.putString("BrandProduct", "brand");
    PreviewProductFragment previewProductFragment = new PreviewProductFragment();
    previewProductFragment.setArguments(bundle);
    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction().addToBackStack("");
    fragmentTransaction.setCustomAnimations(R.anim.enter_right_to_left, R.anim.exit_right_to_left);
    fragmentTransaction.replace(R.id.tabbed_framelayout, previewProductFragment);
    fragmentTransaction.commit();
}


}

BrandProfileViewPagerAdapter это мой viewPager адаптер:

 public class BrandProfileViewPagerAdapter extends FragmentStatePagerAdapter {

private int tabCount;
public BrandProfileViewPagerAdapter(@NonNull FragmentManager fm, int tabs) {
    super(fm, tabs);
    this.tabCount=tabs;
}

@NonNull
@Override
public Fragment getItem(int position) {
    switch (position){
        case 0:
            BrandProductFragment brandProductFragment = new BrandProductFragment();
            return brandProductFragment;
        case 1:
            BrandProfileFragment brandProfileFragment= new BrandProfileFragment();
            return brandProfileFragment;
        default:
            return null;
    }
}

@Override
public int getCount() {
    return tabCount;
}
}

До:

enter image description here

После: enter image description here

...