我有一个片段,我试图添加到一个视图。

FragmentManager fragMgr=getSupportFragmentManager();
feed_parser_activity content = (feed_parser_activity)fragMgr
                                    .findFragmentById(R.id.feedContentContainer);
FragmentTransaction xaction=fragMgr.beginTransaction();

if (content == null || content.isRemoving()) {
    content=new feed_parser_activity(item.getLink().toString());
    xaction
        .add(R.id.feedContentContainer, content)
        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        .addToBackStack(null)
        .commit();
    Log.e("Abstract", "DONE");
}

当这段代码执行时,我在调试中得到以下错误。

java.lang.IllegalArgumentException: No view found for id 0x7f080011 
   for fragment feed_parser_activity{41882f50 #2 id=0x7f080011}

feed_parser_activity是一个片段,在xml中被设置为片段布局。 我使用FragmentActivity来托管持有feed_parser_layout的片段布局。 我上面写的对吗?


当前回答

我修复了这个错误,我使用commitNow()代替commit()。

mFragment.getChildFragmentManager()
  .beginTransaction()
  .replace(R.id.main_fragment_container,fragment)
  .commitNowAllowingStateLoss();

commitNow是一个同步方法,commit()是一个异步方法。

其他回答

我在另一个线程上读到的答案与此类似,当我遇到这个问题时,它涉及到布局xml。

你的日志显示“没有为id 0x7f080011找到视图”。

打开gen->包->R.java->id,然后查找id 0x7f080011。

当我遇到这个问题时,这个id属于activity_main.xml文件中的FrameLayout。

FrameLayout没有一个ID(没有声明android: ID = "blablabla")。

确保所有布局中的所有组件都有id,特别是logcat中引用的组件。

在我的例子中,我在回收器视图项中有一个SupportMapFragment(我使用了较低开销的“liteMode”,它使地图看起来是非交互式的,几乎像一个静态图像)。我使用了正确的FragmentManager,一切看起来都很正常……用一个小列表。当项目列表超过屏幕高度时,我在滚动时开始遇到这个问题。

Turned out, it was because I was injecting a dynamic SupportMapFragment inside a view, which was inside another fragment, to get around some issues I was having when trying to declare it statically in my XML. Because of this, the fragment placeholder layout could only be replaced with the actual fragment once the view was attached to the window, i.e. visible on screen. So I had put my code for initialising the SupportMapFragment, doing the Fragment replace, and calling getMapAsync() in the onAttachedToWindow event.

我忘记做的是确保我的代码不会运行两次。例如,在onAttachedToWindow事件中,在尝试创建它的新实例并进行片段替换之前,检查我的动态SupportMapFragment是否仍然为空。当项目离开RecyclerView顶部时,它将从窗口中分离,然后当您回滚到它时重新连接,因此此事件将触发多次。

一旦我添加了空检查,它只发生一次每个RecyclerView项目和问题消失了!TL;博士!

我修复了这个错误,我使用commitNow()代替commit()。

mFragment.getChildFragmentManager()
  .beginTransaction()
  .replace(R.id.main_fragment_container,fragment)
  .commitNowAllowingStateLoss();

commitNow是一个同步方法,commit()是一个异步方法。

以防有人和我犯同样愚蠢的错误;检查你没有覆盖活动内容的某处(即寻找额外的调用setContentView)

在我的例子中,由于粗心的复制和粘贴,我使用了DataBindingUtil。setContentView在我的片段,而不是DataBindingUtil。膨胀,这会打乱活动的状态。

在我的例子中,我使用了一个片段类文件来声明一个listview适配器类。 我只是为公共适配器类使用了一个不同的文件,错误就消失了。