androidandroid-fragmentsnavigation-drawerpagerslidingtabstrip

Selecting item of sliding tabs menu from navigation drawer with some fragment


I have a project navigation drawer using library (https://github.com/mikepenz/MaterialDrawer) with sliding tab which contained 3 fragment (HomeFragment, LiveFragment, MovieFragment).

I was created navigation drawer in MainActivity.class there are some items (Home, Live TV, Movie). I want when i click item Home from navigation drawer and then go to HomeFragment. I have tried with code below but nothing happen when i click item Home from navigation drawer. Please help me to resolve this problem. Thank you :)

this is my MainAactivity.class

public class MainActivity extends AppCompatActivity{
public final static int NAV_ID_FRAG_ONE = 1;
public final static int NAV_ID_FRAG_TWO = 2;
public final static int NAV_ID_FRAG_THREE = 3;
public final static int NAV_ID_ABOUT_ACTIVITY = 6;

Toolbar toolbar;
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
private Drawer result;
private AccountHeader headerResult;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    toolbar.setTitle("JMN Anywhere");
    setSupportActionBar(toolbar);


    mViewPager = (ViewPager) findViewById(R.id.vp_tabs);
    mViewPager.setAdapter(new TabAdapter(getSupportFragmentManager(), this));

    mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.st1_tabs);
    mSlidingTabLayout.setDistributeEvenly(true);//meratakan posisi icon
    mSlidingTabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
    mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.slidingcolor));
    mSlidingTabLayout.setCustomTabView(R.layout.tab_view, R.id.tv_tab);
    mSlidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    mSlidingTabLayout.setViewPager(mViewPager);
    //Navigation Drawer
    //Header
    AccountHeader headerResult = new AccountHeaderBuilder()
            .withActivity(this)
            .withCompactStyle(false)
            .withSavedInstance(savedInstanceState)
            .withThreeSmallProfileImages(false)
            .withHeaderBackground(R.drawable.header)
            .build();

    //List Drawer
    Drawer result = new DrawerBuilder()
            .withActivity(this)
            .withToolbar(toolbar)
            .withDisplayBelowStatusBar(true)
            .withActionBarDrawerToggleAnimated(true)
            .withDrawerGravity(Gravity.LEFT)
            .withSavedInstance(savedInstanceState)
            .withAccountHeader(headerResult)
            .withHasStableIds(true)
            .withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
            .addDrawerItems(//set item drawer
                    new PrimaryDrawerItem().withName("Home").withDescription("Beranda").withIcon(R.drawable.ic_home_black_48dp).withIdentifier(NAV_ID_FRAG_ONE).withSelectable(false),
                    new PrimaryDrawerItem().withName("Live TV").withDescription("Siaran Televisi").withIcon(R.drawable.ic_live_tv_black_48dp).withIdentifier(NAV_ID_FRAG_TWO).withSelectable(false),
                    new PrimaryDrawerItem().withName("Movies").withDescription("Film-film").withIcon(R.drawable.ic_local_movies_black_48dp).withIdentifier(NAV_ID_FRAG_THREE).withSelectable(false),
                    new ExpandableDrawerItem().withName("Categories").withLevel(2).withIdentifier(4).withSelectable(false).withSubItems(
                            new SecondaryDrawerItem().withName("Action").withLevel(3).withIdentifier(2000),
                            new SecondaryDrawerItem().withName("Comedy").withLevel(3).withIdentifier(2001)
                    ),
                    new SectionDrawerItem().withName("Others"),
                    new SecondaryDrawerItem().withName("Account").withIcon(R.drawable.ic_account_box_black_48dp).withIdentifier(5).withSelectable(false),
                    new SecondaryDrawerItem().withName("About").withIcon(R.drawable.ic_info_black_48dp).withIdentifier(NAV_ID_ABOUT_ACTIVITY).withSelectable(false),
                    new SecondaryDrawerItem().withName("Logout").withIcon(R.drawable.ic_exit_to_app_black_48dp).withIdentifier(7).withSelectable(false)
            )
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public boolean onItemClick(View view, int i, IDrawerItem drawerItem) {
                    Fragment fragment = null;

                    switch ((int) drawerItem.getIdentifier()) {
                        case NAV_ID_FRAG_ONE:
                            fragment = new HomeFragment();
                            break;
                        case NAV_ID_FRAG_TWO:
                            fragment = new LiveFragment();
                            break;
                        case NAV_ID_FRAG_THREE:
                            fragment = new MovieFragment();
                            break;
                        case NAV_ID_ABOUT_ACTIVITY:
                            Intent intent = new Intent(MainActivity.this, AboutActivity.class);
                            startActivity(intent);
                            break;
                    }

                    return false;
                }
            })
            .withSelectedItem(1)
            .withFireOnInitialOnClick(true)
            // add the items we want to use with our Drawer
            .build();

    new RecyclerViewCacheUtil<IDrawerItem>().withCacheSize(2).apply(result.getRecyclerView(), result.getDrawerItems());

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            // User chose the "Settings" item, show the app settings UI...
            Intent in = new Intent("com.ajjunaedi.jmnanywhere.AboutActivity");
            startActivity(in);
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

}


Solution

  • You need to add FragmentManager to add/remove/replace a fragment.

            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.fragment,fragment).commit();
    

    getSupportFragmentManager() = Return the FragmentManager for interacting with fragments associated with this activity.

    .beginTransaction() = Start a series of edit operations on the Fragments associated with this FragmentManager.

    R.id.fragment is the id of the container where you be putting your fragment.

    for more info refer to this post - What does FragmentManager and FragmentTransaction exactly do?

    EDIT: you will add this after your switch statement. I hope this is the answer that you are looking for.

    Add this to your xml file. inside the baselayout

    <RelativeLayout
        android:id="@+id/fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    

    Resize it to your desire. or you can simply add the line android:id="@+id/fragment" to your baselayout.