通过TabLayout到ViewPager的数据传输(适配器:FragmentPagerAdapter)

时间:2019-06-06 16:58:02

标签: android android-viewpager

我正在尝试通过TabLayout显示ViewPager。每个选项卡代表零件类别。也就是说,选项卡1,2,3,...是Battery,Brake,Wiper等类别,它们扩展了Parts类。但是,我只需要一个ViewPager,它应该显示有关所选选项卡的信息。

因此,当我更改选项卡时,它应该更改ViewPager片段内的数据。 (ViewPager由FragmentPagerAdapter改编)。这是我到目前为止尝试过的。

在这里调用ViewPager和TabLayout。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.frag_main_car_manager, container, false);

    activity = (MainActivity) getActivity();

    manager_layout = view.findViewById(R.id.manager_tab_layout);
    managerPager = view.findViewById(R.id.managerPager);

    parts_list_ex = new ArrayList<>(); 

    parts_list_ex.add(new Battery());
    parts_list_ex.add(new Brake());
    parts_list_ex.add(new Wiper());

    // These are the 2 fragments for the viewpager
    progressFragment = new ManagerProgressFragment(parts_list_ex.get(0));
    helperFragment = new ManagerHelperFragment(parts_list_ex.get(0));

    // since this is also a fragment
    manager = getChildFragmentManager();


    fragmentList = new ArrayList<>();
    fragmentList.add(progressFragment);
    fragmentList.add(helperFragment);


    adapter = new PartsManagerPagerAdapter(activity, manager, fragmentList);

    managerPager.setAdapter(adapter);
    manager_layout.setOnTabSelectedListener(tabListener);

    return view;
}

这是我的TabLayout.OnTabSelectedListener tabListener。

TabLayout.OnTabSelectedListener tabListener = new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int i = tab.getPosition();

        Parts selectedParts = parts_list_ex.get(i);

        progressFragment = new ManagerProgressFragment(selectedParts);
        helperFragment = new ManagerHelperFragment(selectedParts);

        fragmentList.clear();
        fragmentList.add(progressFragment);
        fragmentList.add(helperFragment);

        adapter.setFragmentList(fragmentList);
        adapter.notifyDataSetChanged();  // I think this is a part that doesn't work.

    }

这是我的适配器。

public class PartsManagerPagerAdapter extends FragmentPagerAdapter {

Activity activity;

ArrayList<Fragment> fragmentList;

public PartsManagerPagerAdapter(Activity activity, FragmentManager manager, ArrayList<Fragment> fragmentList) {

    super(manager);

    this.activity = activity;

    this.fragmentList = fragmentList;

}

@Override
public Fragment getItem(int position) {

    return fragmentList.get(position);

}

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


public void setFragmentList(ArrayList<Fragment> fragmentList) {
    this.fragmentList = fragmentList;
}

public ArrayList<Fragment> getFragmentList() {
    return this.fragmentList;
}
}

在创建页面时没有显示错误,但是没有传输数据!即使更改标签,它仍会显示第一个标签的信息。我认为adapter.notifyDataSetChanged()无法正常工作。

我尝试了很多解决方案,但这是我得到的最好的解决方案。还有其他方法吗?

0 个答案:

没有答案