如何在触发onNavigationItemSelected时加载片段?

时间:2017-10-28 10:30:54

标签: java android android-fragments

我在Android上创建了新的标签项目,它在我的MainActivity中为我提供了以下内容:

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    return true;
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                    return true;
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_notifications);
//                    Intent i = new Intent(getBaseContext(), PostActivity.class);
//                    startActivity(i);
                    return true;
            }
            return false;
        }

我想加载不同的布局。我的问题是,片段类应该扩展哪个类?是Fragment吗?还是FragmentActivity

如何在onNavigationItemSelected中加载?旧方式为return new FragmentName(),但由于onNavigationItemSelected返回boolean类型

,因此无效

2 个答案:

答案 0 :(得分:0)

与导航抽屉相同,创建布局,框架布局和我在下面发送的调用片段。 取代

mTextMessage.setText(R.string.title_home);

调用片段

 Fragment fragment = new Fragment() ;
                fragment.setCategoryItemListener(MainActivity.this);
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.frame, fragment, "HOME").commit();

答案 1 :(得分:0)

在switch case中调用此函数并传递片段对象

public void moveFragment(Fragment fragment, String fragmentname) {
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
       fragmentTransaction.setCustomAnimations(R.anim.abc_fade_in,
                R.anim.abc_fade_out);
        fragmentTransaction.replace(R.id.content_frame,
                fragment);
        fragmentTransaction.commitAllowingStateLoss();

    }

仅使用片段而非片段活动