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

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


当前回答

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

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

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

其他回答

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

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

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

使用导航库,当NavHostFragment没有id时,问题就会出现。

错误的声明:

<fragment               
     android:name="androidx.navigation.fragment.NavHostFragment"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     app:navGraph="@navigation/myGraph"/>

正确的声明:

<fragment
     android:id="@+id/myId"               
     android:name="androidx.navigation.fragment.NavHostFragment"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     app:navGraph="@navigation/myGraph"/>

当你从一个片段中调用另一个片段时,就会发生这种情况。

使用:

getActivity().getSupportFragmentManager().beginTransaction();

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

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

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

我从com.android.support:support-v4:21.0.0升级到com.android.support:support-v4:22.1.1时遇到了这个错误。

我不得不改变我的布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container_frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</FrameLayout> 

:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</FrameLayout> 

所以布局必须有一个子视图。我猜他们在新图书馆里强制这么做了。