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

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的片段布局。 我上面写的对吗?


当前回答

当你没有在app_bar_main.xml中放入<include layout="@layout/your_fragment_layout"/>时,也会发生这个问题

其他回答

如果您传递给FragmentTransaction的布局ID也会发生此异常。replace(int ID, fragment)存在于其他正在膨胀的布局中。确保布局ID是唯一的,它应该工作。

在我们的例子中,我们清除/损坏了class.dex文件以及gradle编译的输出。由于缓存重新编译没有尝试,因此没有错误,但apk没有所需的文件,导致这个令人困惑的错误。一个gradle resync和新的构建清除了我们所有的错误。

//快乐编码

我也有这个问题,直到我意识到我在FragmentActivity的onCreate()方法的setContentView()中指定了错误的布局。

传入FragmentTransaction.add()的id,在您的示例中是R.id。feedContentContainer,必须是setContentView()中指定的布局的子元素。

您没有向我们展示onCreate()方法,因此这可能是相同的问题。

这个页面似乎是发布关于片段IllegalArgumentException的建议的一个很好的中心位置。还有一件事你可以试试。这是最后对我有用的方法:

我忘了我有一个单独的横向布局文件。在我添加了我的FrameLayout容器之后,这个片段也工作了。


On a separate note, if you have already tried everything else suggested on this page (and the entire Internet, too) and have been pulling out your hair for hours, consider just dumping these annoying fragments and going back to a good old standard layout. (That's actually what I was in the process of doing when I finally discovered my problem.) You can still use the container concept. However, instead of filling it with a fragment, you can use the xml include tag to fill it with the same layout that you would have used in your fragment. You could do something like this in your main layout:

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <include layout="@layout/former_fragment_layout" />

</FrameLayout>

其中former_fragment_layout是您试图在片段中使用的XML布局文件的名称。有关更多信息,请参见使用include重用布局。

有时是因为你在使用一个BottomNavigationView。如果你从导航中打开Intent,在那个活动中打开一个片段

transaction.replace(R.id.container,new YourFragment());

那么Activity将无法找到你正在使用的导航方法。

解决方案:将活动更改为片段,并在应用程序中使用addOnBackStack处理导航。如果你已经实现了Jetpack导航,只需在项目中使用片段。