FragmentTransaction.replace() not working

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

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;

}

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

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

share improve this question
 

2 Answers

up vote 10 down vote accepted

I had a similar problem.

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

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

You can also have a look here.

Hope this helps.

share improve this answer
 

An other problem that solved the issue in my case were diffentent API imports.

Make sure, that you use "support.v4" or the "original" implementations from API 11 and do not mix them. (this can happen, in my case: TransactionManager was v4 and the Activity an older version, or the other way around)

share improve this answer
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值