Обновите или управляйте каждым пейджером данных viewpager - PullRequest
0 голосов
/ 28 сентября 2018

У меня проблема с ViewPager.У меня есть просмотрщик с количеством представлений (вкладок), созданных в соответствии с размером агентств в соответствии с содержимым JSON, который извлекается.Каждая страница представляет агентство (см. JSON ниже).Для каждой страницы я хочу иметь возможность отображать название агентства и изображения моделей.Я правильно получаю названия агентств на каждой странице, но для фотографий моделей одинаковые изображения дублируются на всех других страницах.

Содержание моего фрагмента:

public class MyFragment extends Fragment {
    private int page, campagneId, agenceId;
    private String agenceName;
    private List<MyModel> models;
    RecyclerView rc;

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page = getArguments().getInt("position", 0);
        campagneId = getArguments().getInt("campagneId", 1);
        Log.e("campagneId", "onCreate: "+campagneId );
        agenceName = agenceName.campagne(getContext(),campagneId).get(page).getagenceNameText();
        agenceId = agenceName.campagne(getContext(),campagneId).get(page).getId();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second, container, false);
        initViews(view, ""+agenceName, agenceId, models);
        return view;
    }

    private void initViews(View view, String agenceName,int id, List<MyModel> modelList) {
        TextView textView=view.findViewById(R.id.tv_agenceName);
        textView.setText(agenceName);
        rc = view.findViewById(R.id.rc_models_id);
        rc.setLayoutManager(new GridLayoutManager(getContext(), 3));
        rc.setAdapter(new MyModeladapter(modelList, R.layout.model_item, getContext()));

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

Моя деятельность:

public class MyActivity extends AppCompatActivity{
    private static final String TAG = "MyActivity";
    private ViewPager viewPager;
    private TabLayout mTabLayout;
    Bundle extra;
    Intent i;
    StepperIndicator indicator;
    private String key;
    private int campagneId;
    ApiService service;
    Context mContext;
    private List<Agence> agences = new ArrayList<>();
    private List<Model> models = new ArrayList<>();
    Call<AgenceModel> call;
    MainPagerAdapter mMainPagerAdapter;
    private String q;
    private List<Model> r;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        service = RetrofitBuilder.createService(ApiService.class);
        mMainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager(), 3,campageId);
        i = getIntent();
        extra = i.getExtras();
        key = extra.getString("key");
        campagneId = extra.getInt("campagneId",1);
        Log.e("campageIdLB", "onCreate: "+campageId );
        viewPager = findViewById(R.id.viewpager);
        mTabLayout =  findViewById(R.id.tabs);
        viewPager.setOffscreenPageLimit(5);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));

        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

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

            }

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

            }
        });

        getDatas(key);
    }

    private void getDatas(String s) {
        Constant.dialog(mContext, getString(R.string.wait));
        Constant.showDialog();
        call = service.getspecificSurvey(s);
        call.enqueue(new Callback<AgenceModel>() {
            @Override
            public void onResponse(Call<AgenceModel> call,
                                   @NonNull Response<AgenceModel> response) {
                Constant.hideDialog();
                if (response.isSuccessful()) {
                    AgenceModel r = response.body();
                    Agences = r.getAgences();
                    for (int i = 0; i < r.getAgences().size(); i++) {
                        mTabLayout.addTab(mTabLayout.newTab().setText("Q " + i));
                        Agence.save(MyActivity.this, Agences.get(i));
                        Models = Agences.get(i).getModels();
                        for (int j = 0; j < Models.size(); j++) {
                            Model.save(MyActivity.this, Models.get(j));
                        }
                    }
                    MainPagerAdapter mMainPagerAdapter = new MainPagerAdapter(
                            getSupportFragmentManager(), mTabLayout.getTabCount(), campagneId);
                    viewPager.setAdapter(mMainPagerAdapter);
                    viewPager.setCurrentItem(0);
                }
                Toast.makeText(mContext, getString(R.string.succesfully),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<AgenceModel> call, Throwable t) {
                Constant.hideDialog();
                Log.d(TAG, "failure" + t.fillInStackTrace());
                Toast.makeText(mContext, getString(R.string.server_error),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Мой MainPagerAdapter:

public class MainPagerAdapter extends FragmentStatePagerAdapter{
    private int mNumOfTabs, campageId;
    private Context mContext;
    private LayoutInflater mLayoutInflater;

    public MainPagerAdapter(FragmentManager fm, int NumOfTabs, int campageId) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
        this.campageId = campageId;
        //this.mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public Fragment getItem(int position) {
        Bundle b = new Bundle();
        b.putInt("position", position);
        b.putInt("campageId", campageId);
        Fragment frag = LeadFragment.newInstance();
        frag.setArguments(b);
        return frag;
    }

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

Пример JSON:

{
    "campagne": {
        "id": 1,
        "year": 2018,
        "author": "Katy Roman",
        "close_date": "2019-03-20",
        "created_at": "2018-08-17 19:58:30",
        "updated_at": "2018-08-17 19:58:30",
        "deleted_at": null,
        "finish": 0
    },
    "agences": [
        {
            "id": 2,
            "agence_id": 1,
            "agence_name": "Fashion Home",
            "created_at": "2018-08-24 15:00:21",
            "updated_at": "2018-09-03 22:26:39",
            "deleted_at": null,
            "models": [
                {
                    "id": 1,
                    "agence_id": 1,
                    "model_id": 2,
                    "name": "Brunette"
                    "age": 25,
                    "picture": "bb-50.png",
                    "created_at": "2018-08-24 15:00:21",
                    "updated_at": "2018-09-03 21:09:28",
                    "deleted_at": null
                },
                {
                    "id": 2,
                    "agence_id": 1,
                    "model_id": 2,
                    "name": "Maria"
                    "age": 21,
                    "picture": "maria.png",
                    "created_at": "2018-08-24 15:00:21",
                    "updated_at": "2018-09-03 21:09:28",
                    "deleted_at": null
                },
            ]
        },
        {
            "id": 2,
            "agence_id": 2,
            "agence_name": "Paris lumière",
            "created_at": "2018-08-24 15:00:21",
            "updated_at": "2018-09-03 22:26:39",
            "deleted_at": null,
            "models": [
                {
                    "id": 3,
                    "agence_id": 2,
                    "model_id": 2,
                    "name": "Angelina"
                    "age": 19,
                    "picture": "angelina-happy-50.png",
                    "created_at": "2018-08-24 15:00:21",
                    "updated_at": "2018-09-03 21:09:28",
                    "deleted_at": null
                },
                {
                    "id": 4,
                    "agence_id": 2,
                    "model_id": 2,
                    "name": "Lauraine"
                    "age": 22,
                    "picture": "miss_l_50.png",
                    "created_at": "2018-08-24 15:00:21",
                    "updated_at": "2018-09-03 21:09:28",
                    "deleted_at": null
                },
                {
                    "id": 5,
                    "agence_id": 2,
                    "model_id": 2,
                    "age": 21,
                    "name": "Laure"
                    "picture": "laure_cop_0.png",
                    "created_at": "2018-08-24 15:00:21",
                    "updated_at": "2018-09-03 21:09:28",
                    "deleted_at": null
                },
            ]
        }
    ]
}
...