在运行时将片段添加到TabLayout

时间:2016-02-13 13:58:22

标签: android android-fragments android-viewpager android-tablayout

我的Activity中有一个TabLayout,它在创建时会显示一个片段,但我需要能够在完成一个操作后添加一个新片段(或者在活动时创建两个片段)创建,但只显示第一个,然后显示第二个。)

我已经尝试将片段添加到viewPagerAdapter然后调用notifyDataSetChanged()方法,它添加了它的标签,但它的标题没有显示在tabLayout中,如果我尝试滑动它,我获得IndexOutOfBoundsException: Invalid index 1, size is 1

有人有建议给我吗?

我的活动,我添加了第一个碎片:

   @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.act_one);

   // Crete a new fragment
   FragmentOne fragmentOne = new FragmentoOne();

   tabLayout = (TabLayout) findViewById(R.id.tabLayout);
   viewPager = (ViewPager) findViewById(R.id.viewPager);

   // Creates the viewPagerAdapter
   viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

   // Adds the fragment to ViewPagerAdapter
   viewPagerAdapter.addFragment(fragmentoOne, "First");
   viewPager.setAdapter(viewPagerAdapter);
   tabLayout.setupWithViewPager(viewPager);

}

这是我尝试添加新片段的地方:

public void onAddFragment2() {

    viewPagerAdapter.addFragment(new FragmentoTwo(), "Second");
    viewPagerAdapter.notifyDataSetChanged();

}

4 个答案:

答案 0 :(得分:0)

如果您尝试使用多个标签构建tabLayout,例如:

enter image description here

您可以使用FragmentsViewPager进行制作。但是,在一个问题中从头开始实施它将是多余的!

完美的解决方案是遵循this tutorial,它确实对我有用,如有任何问题,您是否应该选择发表评论!

希望它有所帮助!

答案 1 :(得分:0)

使用setAdapter

添加适配器后再次设置适配器

答案 2 :(得分:0)

这很重要,如果您有3个片段,请在适配器中写入3。

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

答案 3 :(得分:0)

要修改一个 FragmentPagerAdapter 的内容,需要使用如下代码:

public class DynamicFragmentPagerAdapter extends PagerAdapter {
    private static final String TAG = "DynamicFragmentPagerAdapter";
  
    private final FragmentManager fragmentManager;
  
    public static abstract class FragmentIdentifier implements Parcelable {
        private final String fragmentTag;
        private final Bundle args;
      
        public FragmentIdentifier(@NonNull String fragmentTag, @Nullable Bundle args) {
            this.fragmentTag = fragmentTag;
            this.args = args;
        }
      
        protected FragmentIdentifier(Parcel in) {
            fragmentTag = in.readString();
            args = in.readBundle(getClass().getClassLoader());
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(fragmentTag);
            dest.writeBundle(args);
        }
      
        protected final Fragment newFragment() {
            Fragment fragment = createFragment();
            Bundle oldArgs = fragment.getArguments();
            Bundle newArgs = new Bundle();
            if(oldArgs != null) {
                newArgs.putAll(oldArgs);
            }
            if(args != null) {
                newArgs.putAll(args);
            }
            fragment.setArguments(newArgs);
            return fragment;
        }

        protected abstract Fragment createFragment();
    }
  
    private ArrayList<FragmentIdentifier> fragmentIdentifiers = new ArrayList<>();

    private FragmentTransaction currentTransaction = null;

    private Fragment currentPrimaryItem = null;

    public DynamicFragmentPagerAdapter(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
    }

    private int findIndexIfAdded(FragmentIdentifier fragmentIdentifier) {
        for (int i = 0, size = fragmentIdentifiers.size(); i < size; i++) {
            FragmentIdentifier identifier = fragmentIdentifiers.get(i);
            if (identifier.fragmentTag.equals(fragmentIdentifier.fragmentTag)) {
                return i;
            }
        }
        return -1;
    }

    public void addFragment(FragmentIdentifier fragmentIdentifier) {
        if (findIndexIfAdded(fragmentIdentifier) < 0) {
            fragmentIdentifiers.add(fragmentIdentifier);
            notifyDataSetChanged();
        }
    }

    public void removeFragment(FragmentIdentifier fragmentIdentifier) {
        int index = findIndexIfAdded(fragmentIdentifier);
        if (index >= 0) {
            fragmentIdentifiers.remove(index);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        return fragmentIdentifiers.size();
    }

    @Override
    public void startUpdate(@NonNull ViewGroup container) {
        if (container.getId() == View.NO_ID) {
            throw new IllegalStateException("ViewPager with adapter " + this
                    + " requires a view id");
        }
    }

    @SuppressWarnings("ReferenceEquality")
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        if (currentTransaction == null) {
            currentTransaction = fragmentManager.beginTransaction();
        }
        final FragmentIdentifier fragmentIdentifier = fragmentIdentifiers.get(position);
        // Do we already have this fragment?
        final String name = fragmentIdentifier.fragmentTag;
        Fragment fragment = fragmentManager.findFragmentByTag(name);
        if (fragment != null) {
            currentTransaction.attach(fragment);
        } else {
            fragment = fragmentIdentifier.newFragment();
            currentTransaction.add(container.getId(), fragment, fragmentIdentifier.fragmentTag);
        }
        if (fragment != currentPrimaryItem) {
            fragment.setMenuVisibility(false);
            fragment.setUserVisibleHint(false);
        }
        return fragment;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        if (currentTransaction == null) {
            currentTransaction = fragmentManager.beginTransaction();
        }
        currentTransaction.detach((Fragment) object);
    }

    @SuppressWarnings("ReferenceEquality")
    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        Fragment fragment = (Fragment) object;
        if (fragment != currentPrimaryItem) {
            if (currentPrimaryItem != null) {
                currentPrimaryItem.setMenuVisibility(false);
                currentPrimaryItem.setUserVisibleHint(false);
            }
            fragment.setMenuVisibility(true);
            fragment.setUserVisibleHint(true);
            currentPrimaryItem = fragment;
        }
    }

    @Override
    public void finishUpdate(@NonNull ViewGroup container) {
        if (currentTransaction != null) {
            currentTransaction.commitNowAllowingStateLoss();
            currentTransaction = null;
        }
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return ((Fragment) object).getView() == view;
    }

    @Override
    public Parcelable saveState() {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("fragmentIdentifiers", fragmentIdentifiers);
        return bundle;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
        Bundle bundle = ((Bundle)state);
        bundle.setClassLoader(loader);
        fragmentIdentifiers = bundle.getParcelableArrayList("fragmentIdentifiers");
    }
}

然后,通常,要真正进行修改(因为 ViewPagers 很古怪),您很可能需要:

viewPager.setAdapter(null);
viewPager.setAdapter(adapter);