2012-11-19 16 views
18

我有一个ListFragment显示用户创建的项目列表。我有一个ListView,它的id设置为“@android:id/list”,TextView的ID为“@android:id/empty”。FragmentTransaction.replace()不起作用

我有一个操作栏按钮来显示一个片段,以允许用户为列表创建更多的条目。这里是onOptionsItemSelected()方法:

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    Fragment frag = null; 

    // Right now I only have code for the addCourse() fragment, will add more soon 
    switch (item.getItemId()) { 
    case R.id.addCourse: 
     frag = new AddCourseFragment(); 
     break; 
    default: 
     return super.onOptionsItemSelected(item); 
    } 

    // The support library is being dumb and replace isn't actually 
    getFragmentManager().beginTransaction() 
     .remove(this).add(getId(), frag).addToBackStack(null).commit(); 
    return true; 

} 

的AddCourseFragment代码如下:

public class AddCourseFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
     View view = inflater.inflate(R.layout.fragment_addcourse, container, false); 
//  if (view.findViewById(R.id.timesFrame)!=null) { 
     Fragment timesFrag = new TimesFragment(); 
     getChildFragmentManager().beginTransaction() 
      .add(R.id.timesFrame, timesFrag).commit(); 
//  } 
    return view; 
    } 
} 

正如预期的那样,当列表是无人居住的,Android的显示在TextView文本。然后我点击添加课程按钮,发生这种情况:enter image description here
它显示空文本以及新的片段。

回答

20

我有类似的问题。

根据this当您需要以编程方式添加Fragments时,您应该将它们添加到现有ViewGroup

因此,我从xml中删除Fragment,并在replace()方法中使用FrameLayout组件。

你也可以看看here

希望这会有所帮助。

2

在我的情况下解决了这个问题的其他问题是diffentent API导入。

请确保您使用“support.v4”或API 11的“原始”实现,并且不要混合它们。 (这可能发生在我的情况:事务管理是v4和活动的旧版本,或周围的其他方法)

0

另一种解决方案是使用的LinearLayout相反片段

<Fragment 
     android:name="path/to.package.MyClass" 
     android:id="@+id/fragmentContainer" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginBottom="100dp" 
     /> 

使用这样的

<LinearLayout 
     android:name="path/to.package.MyClass" 
     android:id="@+id/fragmentContainer" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginBottom="100dp" 
     /> 
3

给背景颜色的childFragment的主布局。

Android这样的:背景= “#FFFFFF”

这为我工作!!!!

0

我解决了改变LinearLayout的RelativeLayout ...希望它有帮助!

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@color/windowBackground"> 


    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/fragment_container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 


</LinearLayout>