使用布局xml动态膨胀片段,无法找到片段

时间:2015-04-02 03:11:22

标签: android android-layout android-fragments

我正在尝试给布局充气,其中包含在其中声明的片段。然后将此布局作为子视图添加到framelayout。虽然片段被正确充气,但我根本无法搜索片段。

class Activity1 extends Activity {
   public void onCreate(...){
     setContentView(R.layout.container);
     mContainer = findViewId(R.id.container);
   }

   public void OnClick(...){
     LayoutInflater.from(this).inflate(R.layout.child, mContainer);
     Fragment f =getSupportFragmentManager().findFragmentById(R.id.container);
     //f is always null
  }
}

layout.container
 <FrameLayout android:id="@+id/container" .../>

layout.child
 <fragment android:name="com.example.child" .../>

我错过了什么吗?

我认为我发现了这个问题,

这是在fragmentmanager代码中

View parent = null;
int containerId = parent != null ? parent.getId() : 0
fragment.mFragmentId = id != 0 ? id : containerId;

所以我想使用布局inflater对片段进行膨胀与使用FragmentManager添加片段的方式不同

1 个答案:

答案 0 :(得分:1)

您需要在java中提供<fragment />元素的id而不是其容器。

在xml布局中为你的片段提供一些id,如下所示:

<fragment android:id="@+id/myFragment" 
          android:name="com.example.child" .../>

按如下方式访问您的片段:

Fragment f =getSupportFragmentManager().findFragmentById(R.id.myFragment);

这将正确地为您提供布局中的非空片段。