FragmentTransaction.replace()不起作用

22
我有一个显示用户创建的项目列表的ListFragment。我有一个id设置为“@android:id/list”的ListView和一个id为“@android:id/empty”的TextView
我有一个操作栏按钮,用于显示片段以允许用户为列表创建更多条目。这是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
它显示空文本以及新片段。

5个回答

24

我也遇到了类似的问题。

根据这里的说法,如果你需要以编程方式添加Fragments,则应将它们添加到现有的ViewGroup中。

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

你也可以在这里查看。

希望这可以帮助你。


3
在我的情况下解决问题的另一个问题是不同的API导入。请确保您使用“support.v4”或API 11的“原始”实现,并且不要混合使用它们。(这可能会发生,在我的情况下:TransactionManager是v4,而Activity是旧版本,或者反过来)

2
给childFragment的主布局设置背景颜色,例如android:background="#FFFFFF"。这对我有用!!!

3
观点仍然存在,你只是看不到它们。 - TheLibrarian

0
另一个解决方案是使用LinearLayout而不是Fragment。
 <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"
         />

0

我把RelativeLayout改成了LinearLayout来解决问题... 希望能帮到你!

<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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接