如何将Fragment标签添加到新创建的实例?

时间:2019-05-26 20:35:07

标签: android android-fragments

如何将标签添加到新创建的实例?

case 0:           
 return FragmentNotifications.newInstance(notifications, mCurrentTime);

新实例:

    public static FragmentNotifications 
                 newInstance(String notificationsArray, long currentTime){

        FragmentNotifications fragment = new FragmentNotifications();
        return fragment;
    }

如何为使用viewpager创建的片段分配名称?

@Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return 
             FragmentNotifications.newInstance(notifications, mCurrentTime);
            case 1:
                return FragmentMessages.newInstance(messages, 
              mCurrentTime);
            case 2:
                return new FragmentProfile();
            default:
                return null;

        }

    }

1 个答案:

答案 0 :(得分:0)

解答此方法的人的功劳和功劳:

How to get existing fragments when using FragmentPagerAdapter

我得到了由android api自动生成的标签名称

@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
// get the tags set by FragmentPagerAdapter
switch (position) {
    case 0:
        String firstTag = createdFragment.getTag();
        break;
    case 1:
        String secondTag = createdFragment.getTag();
        break;
}
// ... save the tags somewhere so you can reference them later
    return createdFragment;
}

确保使用getChildFragmentManager引用它,否则返回null 我花了大约2个小时来找出为什么findFragmentByTag返回null的原因