I want use NavidationDrawer for application menu, but when click on NavigationItems not action! I want when click on NavigationItems, start other Activities.
Main XML :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/backgroundPrimary"
tools:context="com.tellfa.dastanak.Activities.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/main_appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|snap"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.tellfa.dastanak.Components.CodeSaz_TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:singleLine="true"
android:textColor="#color/textLight"
android:textSize="25sp" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/main_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#color/tabIndicatorColor" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/main_viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/menu_header"
app:itemIconTint="#color/colorPrimary"
app:itemTextColor="#color/colorPrimary"
app:menu="#menu/menu_main_page" />
</android.support.v4.widget.DrawerLayout>
Main code :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar toolbar;
private DrawerLayout mDrawerLayout;
private ViewPager viewPager;
private TabLayout tabLayout;
private DataBase dataBase;
private Cat1_frag_AsyncTask task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataBase = new DataBase(this);
try {
dataBase.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
TextView toolbar_text = (TextView) findViewById(R.id.toolbar_title);
toolbar_text.setText(R.string.app_name_fa);
final ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("");
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_driver);
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
viewPager = (ViewPager) findViewById(R.id.main_viewPager);
if (viewPager != null) {
setupViewPager(viewPager);
}
tabLayout = (TabLayout) findViewById(R.id.main_tabs);
if (tabLayout != null) {
tabLayout.setupWithViewPager(viewPager);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
case R.id.action_recyclerView:
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_recyclerView:
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
}
return onNavigationItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Main_frag_adapter mainFragAdapter = new Main_frag_adapter(getSupportFragmentManager());
mainFragAdapter.addFragment(new Cat1_fragment_recycler(), "آموزنده");
mainFragAdapter.addFragment(new Cat2_fragment_recycler(), "عاشقانه");
mainFragAdapter.addFragment(new Cat3_fragment_recycler(), "بزرگان");
mainFragAdapter.addFragment(new Cat4_fragment_recycler(), "متفرقه");
viewPager.setAdapter(mainFragAdapter);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void forceRTLIfSupported() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
}
How can i it? tnx <3
put this line
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
in
private void setupDrawerContent(NavigationView navigationView)
so updated method is like:
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
mDrawerLayout.closeDrawers();
return true;
}
});
}
Related
I'm trying to add clickable items from menu.xml. It just not working, even Toast effect.
Layout is copy/paste below so you can check it.
There is my MainActivity.java when Im trying using id's.
MainActivity:
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private SectionsPagerAdapter mSectionsPagerAdapter;
private static final String TAG = "MainActivity";
private ViewPager mViewPager;
ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.hamburgermenu);
DrawerLayout drawerLayout = findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
tabLayout.getTabAt(0).setText("Home").setIcon(R.drawable.homeicon);
tabLayout.getTabAt(1).setText("Section 1").setIcon(R.drawable.explorer);
tabLayout.getTabAt(2).setText("Section 2").setIcon(R.drawable.innovator);
tabLayout.getTabAt(3).setText("Section 3").setIcon(R.drawable.collar);
tabLayout.setTabTextColors(getResources().getColorStateList(R.color.white));
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.dashboard:
Intent intentExplorer = new Intent(this, Tab1Explorer.class);
startActivity(intentExplorer);
break;
case R.id.action_search:
//Display Toast for test
Log.d(TAG,"test");
Toast.makeText(this,"Search!", Toast.LENGTH_SHORT).show();
break;
case R.id.action_help:
Intent intentContact = new Intent(this,Tab3Collar.class);
startActivity(intentContact);
break;
case R.id.action_about:
Toast.makeText(this,"This is simple About Demo", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(this,"XYZ", Toast.LENGTH_LONG).show();
return super.onOptionsItemSelected(item);
}
Toast.makeText(this,"XYZ", Toast.LENGTH_LONG).show();
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
Tab0Home tab0 = new Tab0Home();
return tab0;
case 1:
Tab1Section tab1 = new Tab1Section();
return tab1;
case 2:
Tab2Section tab2 = new Tab2Section();
return tab2;
case 3:
Tab3Section tab3 = new Tab3Section();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
// Show 4 total pages.
return 4 ;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Home";
case 1:
return "Section11";
case 2:
return "Section22";
case 3:
return "Section33";
}
return null;
}
}
}
menu_main.xml file looks fine. I have android:id's, icons, titles...
Activity_main.xml file looks:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:title="#string/app_name"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextAppearance="#style/CustomTextStyle">
<android.support.design.widget.TabItem
android:id="#+id/tabItem0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_0" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start">
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/white"
app:menu="#menu/menu_main">
</android.support.design.widget.NavigationView>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
I just want to display for example Toast when I click "Search" from Menu, but it not working. It just colapse hamburger menu without effect.
What should I change?
The navigation view does not use the onOptionsItemSelected method, instead you need to call navigationView.setOnNavigationItemSelectedListener
I have implemented a drawer layout whereby when I click a navigation view item a tab layout opens up. The tablayout comes in fine but the problem is when i click the back button of the tab layout the application crashes with No drawer view found with gravity LEFT. Also I have noticed that there is a bit of a lag when the navigation drawer closes when the tab layout comes in, the drawer does not close smoothly.
Below is my java code and xml:
public class Navigation extends AppCompatActivity implements
ItemFragment.OnHeadlineSelectedListener,
SortFragment.OnHeadlineSelectedListener{
private static final String TAG = Navigation.class.getSimpleName();
Toolbar toolbar;
FragmentManager mFragmentManager;
private TextView mCounter;
private ImageView cart;
FragmentTransaction mFragmentTransaction;
public int id, tabPosition = 0, tabPositionNavigation = 0;
private String drinkToSort = "empty";
SharedPreferences preferences;
private LocalStore localStore;
private String userName, email, location;
private String phone;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation);
localStore = new LocalStore(this);
id = localStore.getLoggedInUser().getId();
userName = localStore.getLoggedInUser().getUserName();
email = localStore.getLoggedInUser().getEmail();
phone = localStore.getLoggedInUser().getPhone();
Log.i(TAG,"USERDATA" + "[" + id + userName + email + phone + location + "]");
relativeLayout = (RelativeLayout) findViewById(R.id.main_content);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle("hello");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("hello");
}
};
Bundle extras = getIntent().getExtras();
if (extras != null) {
this.tabPosition = extras.getInt("tabPosition");
this.tabPositionNavigation = extras.getInt("tabPositionNavigation");
this.drinkToSort = extras.getString("drinkToSort");
Log.d(TAG, tabPosition + tabPositionNavigation + drinkToSort);
}
Bundle bundle = new Bundle();
bundle.putString("drinkToSort", drinkToSort);
LiquorFragment obj = new LiquorFragment();
obj.setArguments(bundle);
int width = getResources().getDisplayMetrics().widthPixels/2;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new NavigationFragment()).commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.details_activity, menu);
RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.cart_no).getActionView();
mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
Log.d("sameSelectionCount", CartCounter.getCounter()+"");
mCounter.setText(""+CartCounter.getCounter());
cart = (ImageView) badgeLayout.findViewById(R.id.cart);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("cart_no","cart_no");
Intent intent = new Intent(getApplicationContext(), ShoppingList.class);
startActivity(intent);
}
});
return true;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume() {
super.onResume();
//TabFragment.viewPager.setCurrentItem(1);
Log.d("landposzq",tabPositionNavigation + "");
if (tabPositionNavigation != 0){
if (tabPositionNavigation == 1){
NavigationFragment.viewPager.setCurrentItem(0);
} else if (tabPositionNavigation == 2){
NavigationFragment.viewPager.setCurrentItem(1);
} else if (tabPositionNavigation == 3){
NavigationFragment.viewPager.setCurrentItem(2);
} else if (tabPositionNavigation == 4){
NavigationFragment.viewPager.setCurrentItem(3);
} else if (tabPositionNavigation == 5){
NavigationFragment.viewPager.setCurrentItem(4);
}
}
}
}
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:openDrawer="start"
android:fitsSystemWindows="true">
<!--Main content-->
<RelativeLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/qb"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar" />
</RelativeLayout>
<!--Navigation Drawer-->
<android.support.design.widget.NavigationView
android:id="#+id/main_drawer"
android:layout_width="290dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#color/white"
app:headerLayout="#layout/drawer_header"
app:itemTextColor="#000000"
app:itemIconTint="#color/qb"
app:menu="#menu/menu_drawer" >
<LinearLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginLeft="20dp"
android:src="#drawable/balloon4"
/>
<TextView
android:id="#+id/free_drinks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffff99"
android:gravity="center_vertical"
android:padding="10dp"
android:drawableRight="#drawable/direction"
android:height="60dp"
android:textSize="18sp"
android:text="GET FREE DRINKS"
android:textColor="#000000"
android:layout_gravity="bottom"
/>
</LinearLayout>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Change your onBackPressed() method as below :
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
I have a working Navigation Drawer through out multiple activities and I am looking to highlight the current Navigation Item Selected after it changes the activity. How can I save the Item Selected Listener through out the whole app while the onCreateDrawer its recreating itself on every other activity?
If you need any other relevant activity or have any feedback, dont hesitate to indulge me!
BaseActivity
public class BaseActivity extends AppCompatActivity {
public NavigationView mNavigationView;
protected ActionBarDrawerToggle mToggle;
protected Toolbar mToolbar;
public DrawerLayout mDrawerLayout;
protected void onCreateDrawer() {
//Instantiate Navigation Drawer
setupNavDrawer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logout) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mToggle.onConfigurationChanged(newConfig);
}
//Set up Navigation Drawer
private void setupNavDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mNavigationView= (NavigationView) findViewById(R.id.navigation_view);
setSupportActionBar(mToolbar);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.setDrawerListener(mToggle);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull final MenuItem item) {
mDrawerLayout.closeDrawers();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (item.getItemId()){
case R.id.nav_home:
Intent intent0 = new Intent(BaseActivity.this, Home.class);
startActivity(intent0.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
mNavigationView.setCheckedItem(R.id.nav_home);
break;
case R.id.nav_settings:
Intent intent1 = new Intent(BaseActivity.this, Settings.class);
startActivity(intent1.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
mNavigationView.setCheckedItem(R.id.nav_settings);
break;
case R.id.nav_selection:
Intent intent2 = new Intent(BaseActivity.this, Selection.class);
startActivity(intent2.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
mNavigationView.setCheckedItem(R.id.nav_selection);
break;
case R.id.nav_privacy_policy:
Intent intent3 = new Intent(BaseActivity.this, PrivacyPolicy.class);
startActivity(intent3.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
mNavigationView.setCheckedItem(R.id.nav_privacy_policy);
break;
default:
Intent intent4 = new Intent(BaseActivity.this, Home.class);
startActivity(intent4.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
mNavigationView.setCheckedItem(R.id.nav_home);
break;
}
}
}, 225);
return true;
}
});
}
}
Home
public class Home extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
super.onCreateDrawer();
}
Selection
public class Selection extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection);
super.onCreateDrawer();
}
Activity_Home.XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/layout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" >
<TextView
android:text="Hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#FFFF"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu"/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Activity_Selection.XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/layout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.app.navigationdrawer.Teste">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" >
<TextView android:text="Selection" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewTeste" />
</RelativeLayout>
<!-- <include layout="#layout/toolbar_actionbar" /> -->
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#FFFF"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu"/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Once I also had similar problem. And here is what worked for me:
Change menu ids and class names as per your situation.
private void setupNavDrawer() {
// ...
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.mainSection:
drawerLayout.closeDrawers();
startNewActivity(MainActivity.class);
break;
case R.id.allGames:
drawerLayout.closeDrawers();
startNewActivity(GamesActivity.class);
break;
return true;
}
});
setNavigationViewCheckedItem();
// .....
}
And here setNavigationViewCheckedItem mehod:
private void setNavigationViewCheckedItem() {
if (this.getClass().equals(MainActivity.class)) {
navigationView.setCheckedItem(R.id.mainSection);
} else if (this.getClass().equals(GamesActivity.class)) {
navigationView.setCheckedItem(R.id.allGames);
}
}
The following code is of BaseActivity and this activity is used to implement navigation drawer for different activity
public class BaseActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private NavigationView navigationView;
private DrawerLayout fullLayout;
private Toolbar toolbar;
private ActionBarDrawerToggle drawerToggle;
private int selectedNavItemId;
#Override
public void setContentView(#LayoutRes int layoutResID) {
fullLayout = (DrawerLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
FrameLayout activityContainer = (FrameLayout) fullLayout.findViewById(R.id.activity_content);
getLayoutInflater().inflate(layoutResID, activityContainer, true);
/**
* Note that we don't pass the child's layoutId to the parent,
* instead we pass it our inflated layout.
*/
super.setContentView(fullLayout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
navigationView = (NavigationView) findViewById(R.id.navigationView);
if (useToolbar())
{
setSupportActionBar(toolbar);
}
else
{
toolbar.setVisibility(View.GONE);
}
setUpNavView();
}
protected boolean useToolbar()
{
return true;
}
protected void setUpNavView()
{
navigationView.setNavigationItemSelectedListener(this);
if( useDrawerToggle()) { // use the hamburger menu
drawerToggle = new ActionBarDrawerToggle(this, fullLayout, toolbar,
R.string.nav_drawer_opened,
R.string.nav_drawer_closed);
fullLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
} else if(useToolbar() && getSupportActionBar() != null) {
// Use home/back button instead
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(getResources()
.getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha));
}
}
protected boolean useDrawerToggle()
{
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
fullLayout.closeDrawer(GravityCompat.START);
selectedNavItemId = menuItem.getItemId();
return onOptionsItemSelected(menuItem);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id)
{
case R.id.action_main:
startActivity(new Intent(this, MainActivity.class));
return true;
case R.id.action_order:
startActivity(new Intent(this, Orders.class));
return true;
case R.id.rate_card:
startActivity(new Intent(this,RateCard.class));
return true;
}
return super.onOptionsItemSelected(item);
}
And here is xml file design which is used for implementation purpose
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="#+id/activity_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="?attr/colorPrimary"
app:theme="#style/MainActionBar"/>
<FrameLayout
android:id="#+id/activity_content"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/menu_base"/>
</android.support.v4.widget.DrawerLayout>
I tried all thing but not getting proper way to implement.Any suggestion how to correct this will be helpful
My main activity consists of a navigation drawer and switching between fragments was working fine. Now i tried to implement Material Searchview using this library which requires the toolbar to be set last inside the xml file. So now my serachview is working fine but onNavigationItemSelected stops working and i cant switch between fragments. If inside the xml i write navigation drawer below the toolbar navigation starts working again but searchview stops working. Please help me.
activity_home.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
<com.miguelcatalan.materialsearchview.MaterialSearchView
android:id="#+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</FrameLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
HomeActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
exploreFragment();
searchView = (MaterialSearchView) findViewById(R.id.search_view);
searchView.setVoiceSearch(false);
searchView.setCursorDrawable(R.drawable.custom_cursor);
searchView.setEllipsize(true);
// searchView.setSuggestions(getResources().getStringArray(R.array.query_suggestions));
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(HomeActivity.this,query,Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//Do some magic
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home,menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
exploreFragment();
} else if (id == R.id.nav_gallery) {
newFragment();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void exploreFragment(){
fragment = new ExploreFragment();
Bundle bundle = new Bundle();
// bundle.putString("loginToken",loginToken);
// bundle.putString("userId", userId);
fragment.setArguments(bundle);
if (fragment != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
}
public void newFragment(){
fragment = new NewFragment();
Bundle bundle = new Bundle();
// bundle.putString("loginToken",loginToken);
// bundle.putString("userId", userId);
fragment.setArguments(bundle);
if (fragment != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.container_body, fragment).commit();
}
}
I think you forgot to add actionviewclass
<item
android:id="#+id/action_search"
android:icon="#drawable/ic_search"
android:title="Search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="com.miguelcatalan.materialsearchview.MaterialSearchView" />