FragmentTransaction.replace()不工作 [英] FragmentTransaction.replace() not working

查看:296
本文介绍了FragmentTransaction.replace()不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ListFragment 显示了由用户创建的项目清单。我有一个的ListView 与它的ID设置为@android:ID /列表和的TextView id为 @android:ID /空。

I have a ListFragment displaying a list of items that created by the user. I have a ListView with it's id set to "@android:id/list" and a TextView with the id "@android:id/empty".

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

I have an action bar button to display a fragment to allow the user to create more entries for the list. Here is the onOptionsItemSelected() method:

@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 code是如下:

The AddCourseFragment code is as follows:

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

正如预期的那样,当列表被填充,机器人展示了的TextView 的文本。然后我打的过程中添加按钮,出现这种情况:
它显示了空文本,以及新的片段。

As expected, when the list is unpopulated, android shows the text in the TextView. I then hit the add course button and this happens:
It shows the empty text as well as the new fragment.

推荐答案

我也有类似的问题。

根据当你需要添加片段编程,你应该将它们添加到现有的的ViewGroup

According to this when you need to add Fragments programmatically, you should add them to an existing ViewGroup.

所以,我辗转于替换片段从XML和使用的FrameLayout 组件()方法。

So I removed the Fragment from the xml and used FrameLayout component in the replace() method.

您还可以看看<一href="http://stackoverflow.com/questions/5293850/fragment-duplication-on-fragment-transaction">here.

希望这有助于。

这篇关于FragmentTransaction.replace()不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆