FragmentTransaction.replace()不工作工作、FragmentTransaction、replace

2023-09-05 00:18:22 作者:[Collapse]崩溃

我有一个 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.

您还可以看看here.

希望这有助于。