【问题标题】:How do I add a Fragment tag to a newly created instance?如何为新创建的实例添加 Fragment 标签?
【发布时间】:2019-05-29 06:32:32
【问题描述】:

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

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;

        }

    }

【问题讨论】:

  • “标签”是什么意思?当您使用FragmentManager 加载片段时,您可以针对片段设置标签值 - 这就是您所指的吗? (看起来像getFragmentManager().beginTransaction().replace(layoutId,frag,"A_TAG").commit();
  • 是的,但是我将如何使用新的实例呢?因为我正在尝试在 viewpager 中创建片段的新实例,所以我不能使用替换
  • 我不明白这个问题 - “标签”用于FragmentManager,作为稍后检索片段的一种方式。 Fragment 本身并没有直接的用途。您可以将标签分配为片段中的常量值,即 ...replace(layoutId,frag,MyFragment.TAG)...
  • 我正在尝试在 viewpager 中获取片段。但是我确定在viewpager创建片段时如何分配它(上面添加了编辑)
  • 我明白了。你看到this SO question on how to retrieve Fragments from a ViewPager的答案了吗?

标签: android android-fragments


【解决方案1】:

对发现此方法的人的回答和致谢:

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

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多