Android标题更改但替换提交后片段保持不变

时间:2016-06-13 01:18:18

标签: android android-fragments navigation-drawer fragmenttransaction

我有一个简单的导航抽屉。当我点击项目来更改当前片段时,它会运行替换命令的代码,但片段不会更改。

以下是我设置导航抽屉的方法:

private void setupNavigationMenu(final Bundle savedInstanceState) {
        final DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.nav_drawer_items);

        // Create the navigation drawer.
        navigationDrawer = new NavigationDrawer(this, toolbar, drawerLayout, mDrawerList,
                R.id.main_fragment_container);

        String[] osArray = {"Discover Tunes", "My Discovered Tunes"};
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
        mDrawerList.setAdapter(mAdapter);

        if (savedInstanceState == null) {
            // Add the home fragment to be displayed initially.
            discoverSongs();
        }

        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0){
                    discoverSongs();
                    drawerLayout.closeDrawers();

                } else {

                    myDiscoveredSongs();
                    drawerLayout.closeDrawers();

                }
            }
        });

如上所示,我有onitemclicklistner运行discoverSongs()和myDiscoveredSongs()函数。当我点击列表时,我可以看到正确的位置正在运行并且正在运行的功能正常。但是,discoverSongs()的片段总是出现。

这是我的discoverSongs()函数:

 public void discoverSongs() {

        final Fragment fragment = new DiscoverSongFragment();

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.main_fragment_container, fragment, DiscoverSongFragment.class.getSimpleName())
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .commit();

        setTitle("Discover Tunes");

我的myDiscoveredSongs()函数如下所示:

public void myDiscoveredSongs() {

    final Fragment fragment = new DiscoverSongFragment();

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.main_fragment_container, fragment, MyDiscoveredSongsFragment.class.getSimpleName())
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            .commit();

    setTitle("My Discovered Tunes");

}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您在myDiscoveredSongs()方法中使用相同的片段名称,因此请更改此行代码

final Fragment fragment = new DiscoverSongFragment();
在inmyDiscoveredSongs()中