I tried to add a submenu on products and the app crashes on start. The problem comes from the submenu created. I dont understand why.
NavigationMenu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/nav_home"
android:title="Home" />
<item android:title="Products"
android:id="#+id/nav_products">
<menu>
<item android:id="#+id/nav_tubeBendingMachines"
android:title="Tub" />
<item android:id="#+id/nav_sectionBendingRolls"
android:title="Sect" />
</menu>
</item>
<item android:id="#+id/nav_tube_data"
android:title="Tube Data" />
<item android:id="#+id/nav_tool_setup"
android:title="Tool Setup" />
<item android:id="#+id/nav_mandrel"
android:title="Mandrel" />
<item android:id="#+id/nav_archive"
android:title="Archive" />
<item android:id="#+id/nav_tool_notes"
android:title="Tool Notes" />
<item android:id="#+id/nav_converter"
android:title="Converter" />
<item android:id="#+id/nav_bend_guide"
android:title="Bend Guide" />
<item android:id="#+id/nav_contact"
android:title="Contact Us" />
<item android:id="#+id/nav_settings"
android:title="Settings"
android:icon="#mipmap/ic_settings_black_24dp"/>
</menu>
Main
public class MainActivity extends AppCompatActivity {
//Side menu
private DrawerLayout mDrawerLayout;
//button side menu
private ActionBarDrawerToggle mToggle;
//toolbar
private Toolbar mToolbar;
//Fragments
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//fragments transaction
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container,new HomeFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
//select which fragment to show based on item id
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.nav_home:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new HomeFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Home");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.nav_settings:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new SettingsFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Settings");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.nav_contact:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new ContactUsFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Contact Us");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.nav_tube_data:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new TubeDataFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Tube Data");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.nav_archive:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new ArchiveFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Archive");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.nav_bend_guide:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new BendGuideFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Bend Guide");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.nav_mandrel:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new MandrelFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Mandrel");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.nav_tool_setup:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new ToolSetupFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Tool Setup");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
case R.id.nav_products:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container,new ProductsFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Products");
item.setChecked(true);
mDrawerLayout.closeDrawers();
break;
}
return true;
}
});
}
//toggle para o menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
CRASH LOGS :
04-20 10:40:45.923 6040-6040/com.example.tiagosilva.amob_android E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tiagosilva.amob_android, PID: 6040
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tiagosilva.amob_android/com.example.tiagosilva.amob_android.MainActivity}: android.view.InflateException: Binary XML file line #38: Binary XML file line #38: Error inflating class android.support.design.widget.NavigationView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: android.view.InflateException: Binary XML file line #38: Binary XML file line #38: Error inflating class android.support.design.widget.NavigationView
Caused by: android.view.InflateException: Binary XML file line #38: Error inflating class android.support.design.widget.NavigationView
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.tiagosilva.amob_android.MainActivity.onCreate(MainActivity.java:34)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassCastException: android.support.design.internal.NavigationMenuPresenter$NavigationMenuSeparatorItem cannot be cast to android.support.design.internal.NavigationMenuPresenter$NavigationMenuTextItem
at android.support.design.internal.NavigationMenuPresenter$NavigationMenuAdapter.appendTransparentIconIfMissing(NavigationMenuPresenter.java:540)
at android.support.design.internal.NavigationMenuPresenter$NavigationMenuAdapter.prepareMenuItems(NavigationMenuPresenter.java:527)
at android.support.design.internal.NavigationMenuPresenter$NavigationMenuAdapter.update(NavigationMenuPresenter.java:460)
at android.support.design.internal.NavigationMenuPresenter.updateMenuView(NavigationMenuPresenter.java:117)
at android.support.design.widget.NavigationView.inflateMenu(NavigationView.java:252)
04-20 10:40:45.923 6040-6040/com.example.tiagosilva.amob_android E/AndroidRuntime:
at android.support.design.widget.NavigationView.<init>(NavigationView.java:174)
at android.support.design.widget.NavigationView.<init>(NavigationView.java:100)
... 25 more
XXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXxXXXXXXXXXXXx
Caused by: android.view.InflateException: Binary XML file line #38:
Binary XML file line #38: Error inflating class
android.support.design.widget.NavigationView
Caused by:
android.view.InflateException: Binary XML file line #38: Error
inflating class android.support.design.widget.NavigationView
REASON:
The problem is in your NavigationMenu.xml. Item nav_settings causes the InflateException. This happened because this item has icon but the above items does not has icons and you have not grouped them together.
SOLUTION:
To solve this InflateException, put menu items nav_tube_data to nav_contact into a group and also you have to give an id to group.
Here is the working XML code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/nav_home"
android:title="Home" />
<item android:title="Products"
android:id="#+id/nav_products">
<menu>
<item android:id="#+id/nav_tubeBendingMachines"
android:title="Tub" />
<item android:id="#+id/nav_sectionBendingRolls"
android:title="Sect" />
</menu>
</item>
<group
android:checkableBehavior="none"
android:id="#+id/group_one">
<item android:id="#+id/nav_tube_data"
android:title="Tube Data" />
<item android:id="#+id/nav_tool_setup"
android:title="Tool Setup" />
<item android:id="#+id/nav_mandrel"
android:title="Mandrel" />
<item android:id="#+id/nav_archive"
android:title="Archive" />
<item android:id="#+id/nav_tool_notes"
android:title="Tool Notes" />
<item android:id="#+id/nav_converter"
android:title="Converter" />
<item android:id="#+id/nav_bend_guide"
android:title="Bend Guide" />
<item android:id="#+id/nav_contact"
android:title="Contact Us" />
</group>
<item android:id="#+id/nav_settings"
android:title="Settings"
android:icon="#drawable/ic_settings_black_24dp"/>
</menu>
OUTPUT:
One suggestion, don't put your resource icons in mipmap folder. mipmap is only for launcher icons. For other resource icons you should use drawable folder.
UPDATE:
I wanted to click Products and it goes to the page showing all the
items related to Products. There is no way to make Products clickable
like the other items like Home, etc...?
Try this:
..................
.............................
<group
android:checkableBehavior="none"
android:id="#+id/group_two">
<item android:title="Products"
android:id="#+id/nav_products" />
<item android:id="#+id/nav_tubeBendingMachines"
android:title="Tub" />
<item android:id="#+id/nav_sectionBendingRolls"
android:title="Sect" />
</group>
................
.......................
Hope this will help~
Related
This links contains the screenshot. It shows the dark places inplace of the icons. The shape of those places is just like that of the icons but icons are not appearing.
MainActivity.java
[private BottomNavigationView.OnNavigationItemSelectedListener
mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_buy:
fragment = new Buy();
break;
case R.id.navigation_orders:
fragment = new Orders();
break;
case R.id.navigation_navigation:
fragment = new Navigation();
break;
case R.id.navigation_chat:
fragment = new Chat();
break;
case R.id.navigation_invite:
fragment = new Invite();
break;
}
final FragmentTransaction transaction =
fragmentManager.beginTransaction();
transaction.replace(R.id.content, fragment).commit();
return true;
}
};]
menu.xml
[<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/navigation_buy"
android:icon="#drawable/buy_ic"
android:title="#string/title_buy"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/navigation_orders"
android:icon="#drawable/orders_ic"
android:title="#string/title_orders"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/navigation_navigation"
android:icon="#drawable/navigation_ic"
android:title="#string/title_navigation"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/navigation_chat"
android:icon="#drawable/chat_ic"
android:title="#string/title_chat"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/navigation_invite"
android:icon="#drawable/invite_ic"
android:title="#string/title_invite"
app:showAsAction="ifRoom"/>
</menu>]
activity_main.xml
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="#color/colorPrimary"
app:itemTextColor="#color/white"
app:menu="#menu/navigation" />
Use itemIconTint instead of app:itemBackground="#color/colorPrimary"
app:itemIconTint="#color/colorPrimary"
Please can someone help me with fragments from the navigation drawer, for some reason I can't get them to work and all the code looks right.
Here is the link to the source code.
Use this code:
navigationView = (NavigationView) findViewById(R.id.navigationView);
navigationView.bringToFront();
Have a look at your MainActivity.java.
You have implemented the callbacks for NavigationView.OnNavigationItemSelectedListener in MainActivity as below,
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// blah blah
}
Also check the setupDrawerContent method.
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
In this method you are creating a local OnNavigationItemSelectedListener.
So you are not using the OnNavigationItemSelectedListener that you have overridden in MainActivity.
The solution is to use this as argument for setNavigationItemSelectedListener. By doing this all your clicks will go the onNavigationItemSelected of MainActivity rather than going to the local onNavigationItemSelected.
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(this);
}
Also move the code in the local onNavigationItemSelected to the onNavigationItemSelected of MainActivity.
So your onNavigationItemSelected will be something like this,
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Handle navigation view item clicks here.
int id = menuItem.getItemId();
menuItem.setChecked(true);
drawerLayout.closeDrawers();
if (id == R.id.nav_home) {
// Handle the home action
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_the_wetlands) {
Toast.makeText(this, "The Wetlands", Toast.LENGTH_SHORT).show();
TheWetlandsFragment theWetlandsFragment = new TheWetlandsFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.relativelayout_for_fragment, theWetlandsFragment, theWetlandsFragment.getTag()).commit();
} else if (id == R.id.nav_the_mistbelt_forests) {
Toast.makeText(this, "The Mistbelt Forests", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Also change your activity_main_drawer_view.xml as follows to solve the multiple selection issue you have in the Navigation Drawer,
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_dashboard"
android:title="Home" />
</group>
<item android:title="Information">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_the_wetlands"
android:icon="#drawable/ic_event"
android:title="The Wetlands" />
<item
android:id="#+id/nav_the_mistbelt_forests"
android:icon="#drawable/ic_event"
android:title="The Mistbelt Forests" />
<item
android:id="#+id/nav_the_grasslands"
android:icon="#drawable/ic_event"
android:title="The Grasslands" />
</group>
</item>
<item android:title="Quick Go To">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_accommodation"
android:icon="#drawable/ic_event"
android:title="Accommodation" />
<item
android:id="#+id/nav_cuisine"
android:icon="#drawable/ic_forum"
android:title="Cuisine" />
<item
android:id="#+id/nav_leisure_activites"
android:icon="#drawable/ic_forum"
android:title="Leisure & Activites" />
<item
android:id="#+id/nav_agri_tourism"
android:icon="#drawable/ic_forum"
android:title="Agri-tourism" />
<item
android:id="#+id/nav_education"
android:icon="#drawable/ic_forum"
android:title="Education" />
<item
android:id="#+id/nav_arts_crafts_decor"
android:icon="#drawable/ic_forum"
android:title="Arts, Crafts & DeCor" />
<item
android:id="#+id/nav_selective_shopping"
android:icon="#drawable/ic_forum"
android:title="Selective Shopping" />
<item
android:id="#+id/nav_for_children"
android:icon="#drawable/ic_forum"
android:title="For Children" />
</group>
</item>
<item android:title="Midlands Animals">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_midlands_birding_checklist"
android:icon="#drawable/ic_dashboard"
android:title="Midlands Birding Checklist" />
<item
android:id="#+id/nav_midlands_mammals_checklist"
android:icon="#drawable/ic_dashboard"
android:title="Midlands Mammals Checklist" />
</group>
</item>
</menu>
Good luck.
Don't use
NavigationUI.setupWithNavController(navigationView, navController);
instead of it do this
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
return false;
}
});
I have also faced the same problem some time back, and at the end i realized that i have not wrote the 2nd line of the following code
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
you make sure you have written the same otherwise your listener will not work
in my case i forgot to initialize navigation menu.
kindly follow following code:
public void initSideMenu() {
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
happy coding...
Make sure you have implement the interface NavigationView.OnNavigationItemSelectedListener.
Second point make sure to add these lines otherwise listnere will not be called.
navigationView=(NavigationView) findviewbyid(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
Add this line
navigationView.bringToFront();
Its works for me
I have this XML.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:checked="true"
android:icon="#drawable/ic_home_black_24dp"
android:title="Home" />
<item
android:id="#+id/nav_search"
android:icon="#drawable/ic_search_black"
android:title="Search Location" />
<item
android:id="#+id/nav_fav"
android:icon="#drawable/ic_favorite"
android:title="Favorites" />
<item
android:id="#+id/nav_recent"
android:icon="#drawable/ic_nav_route"
android:title="Recent Location" />
<item
android:id="#+id/nav_route"
android:icon="#drawable/ic_place"
android:title="Route" />
</group>
<item android:title="Others">
<menu>
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_settings"
android:title="Settings" />
<item
android:id="#+id/nav_about"
android:icon="#android:drawable/ic_menu_send"
android:title="About" />
</menu>
</item>
</menu>
But when selecting the nav_settings,
the item is not check.
The item should be check just like the other items above.
This is my code on setting the item checked.
The fragment will just work fine.
but the selector on the nav_settings didn't work..
public void selectDrawerItem(MenuItem menuItem) {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_home:
fragmentClass = FragmentMap.class;
setTitle("Map");
break;
case R.id.nav_search:
fragmentClass = FragmentSearchLoc.class;
Global.setCurrentItem =2;
break;
case R.id.nav_recent:
fragmentClass = FragmentSearchLoc.class;
Global.setCurrentItem =0;
break;
case R.id.nav_fav:
fragmentClass = FragmentSearchLoc.class;
Global.setCurrentItem =1;
break;
case R.id.nav_route:
fragmentClass = FragmentRoute.class;
setTitle("Routing");
break;
case R.id.nav_settings:
fragmentClass = FragmentSettings.class;
setTitle("Settings");
break;
default:
fragmentClass = FragmentMap.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
drawer
menuItem.setChecked(true);
drawer.closeDrawers();
}
I don't think nesting items like your code is allowed.
If you do like below, it may work:
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_settings"
android:title="Settings" />
<item
android:id="#+id/nav_about"
android:icon="#android:drawable/ic_menu_send"
android:title="About" />
</group>
Navigation Drawer Is Not With AppCompactActivity
My Code is
activity_main.xml
<android.support.v4.widget.DrawerLayout 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/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
>
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar"
/>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer"
/>
</android.support.v4.widget.DrawerLayout>
content_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="INBOX"
android:padding="8dp"
android:textColor="#fff"
android:background="#color/PrimaryColor"
android:textSize="28sp"
android:id="#+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
tool_bar.xml
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/AppTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/PrimaryColor"
android:minHeight="#dimen/abc_action_bar_default_height_material" />
header.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="190dp"
android:background="#drawable/background_material"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="76dp"
android:layout_height="76dp"
android:src="#drawable/profile"
app:border_color="#FF000000"
android:layout_marginLeft="24dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginStart="24dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Geevarughese"
android:textSize="14sp"
android:textColor="#FFF"
android:textStyle="bold"
android:gravity="left"
android:paddingBottom="4dp"
android:id="#+id/username"
android:layout_above="#+id/email"
android:layout_alignLeft="#+id/profile_image"
android:layout_alignStart="#+id/profile_image" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nestofrubin#live.com"
android:id="#+id/email"
android:gravity="left"
android:layout_marginBottom="8dp"
android:textSize="14sp"
android:textColor="#fff"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/username"
android:layout_alignStart="#+id/username" />
</RelativeLayout>
MainActivity.java
package com.example.geevarughese.nav;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.inbox:
Toast.makeText(getApplicationContext(),"Inbox Selected",Toast.LENGTH_SHORT).show();
ContentFragment fragment = new ContentFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
return true;
// For rest of the options we just show a toast on click
case R.id.starred:
Toast.makeText(getApplicationContext(),"Stared Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.sent_mail:
Toast.makeText(getApplicationContext(),"Send Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.drafts:
Toast.makeText(getApplicationContext(),"Drafts Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.allmail:
Toast.makeText(getApplicationContext(),"All Mail Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.trash:
Toast.makeText(getApplicationContext(),"Trash Selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.spam:
Toast.makeText(getApplicationContext(),"Spam Selected",Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#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) {
// 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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ContentFragment.java
package com.example.geevarughese.nav;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Admin on 04-06-2015.
*/
public class ContentFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.content_fragment,container,false);
return v;
}
}
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat">
<item name="android:colorPrimary">#color/PrimaryColor</item>
<item name="android:colorPrimaryDark">#color/PrimaryDarkColor</item>
<item name="android:statusBarColor">#android:color/transparent</item>
<!-- Customize your theme here. -->
</style>
</resources>
drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/inbox"
android:checked="false"
android:icon="#drawable/ic_3d_rotation_black_24dp"
android:title="Inbox" />
<item
android:id="#+id/starred"
android:checked="false"
android:icon="#drawable/ic_accessibility_black_24dp"
android:title="Starred" />
<item
android:id="#+id/sent_mail"
android:checked="false"
android:icon="#drawable/ic_account_balance_black_24dp"
android:title="Sent Mail" />
<item
android:id="#+id/drafts"
android:checked="false"
android:icon="#drawable/ic_account_circle_black_24dp"
android:title="Draft" />
<item
android:id="#+id/allmail"
android:checked="false"
android:icon="#drawable/ic_add_shopping_cart_black_24dp"
android:title="All Mail" />
<item
android:id="#+id/trash"
android:checked="false"
android:icon="#drawable/ic_alarm_add_black_24dp"
android:title="Trash" />
<item
android:id="#+id/spam"
android:checked="false"
android:icon="#drawable/ic_android_black_24dp"
android:title="Spam" />
</group>
</menu>
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="PrimaryColor">#2196F3</color>
<color name="PrimaryDarkColor">#1976D2</color>
</resources>
I tried everything that i know. but the app doesn't opens.
My logcat error is:
08-19 02:11:09.109 8809-8809/com.example.geevarughese.nav E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.geevarughese.nav, PID: 8809
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.geevarughese.nav/com.example.geevarughese.nav.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.AppCompatDelegateImplBase.onCreate(AppCompatDelegateImplBase.java:122)
at android.support.v7.app.AppCompatDelegateImplV7.onCreate(AppCompatDelegateImplV7.java:146)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:59)
at com.example.geevarughese.nav.MainActivity.onCreate(MainActivity.java:23)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.geevarughese.nav" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Replace your styles.xml file with this.
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:colorPrimary">#color/PrimaryColor</item>
<item name="android:colorPrimaryDark">#color/PrimaryDarkColor</item>
<item name="android:statusBarColor">#android:color/transparent</item>
<!-- Customize your theme here. -->
</style>
I'm implementing material design to my application. I replaced native ActionBar with new android Toolbar. Menu items are added, onOptionsItemSelected works perfectly. But when I click overflow icon or item with several more menu items, the application crashes.
toolbar screenshot: https://www.dropbox.com/s/smay4k1qwkd8amz/Screenshot_2015-05-29-11-31-55.png?dl=0
activity_main.xml
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="#color/my_primary"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
</android.support.v7.widget.Toolbar>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"
/>
</LinearLayout>
styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="AppTheme.Base">
</style>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/my_primary</item>
<item name="colorPrimaryDark">#color/my_primary_dark</item>
<item name="colorAccent">#color/my_accent</item>
</style>
</resources>
MyActivity.java
public class MyActivity extends ActionBarActivity {
private Toolbar toolbar;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
}
menu\main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:Compat="http://schemas.android.com/apk/res/com.example.myapp">
<item
android:id="#+id/action_add"
android:title="Add"
android:icon="#android:drawable/ic_menu_add"
Compat:showAsAction="always"/>
<item
android:title="Items"
android:icon="#android:drawable/ic_menu_agenda"
Compat:showAsAction="always"
>
<menu>
<item
android:id="#+id/action_1"
android:title="item1"/>
<item
android:id="#+id/action_2"
android:title="item2"/>
</menu>
</item>
<item
android:id="#+id/action_about"
android:title="About"
android:icon="#android:drawable/ic_menu_help"
Compat:showAsAction="never"/>
</menu>
The following message is shown after the crash:
05-29 11:21:18.012 31469-31469/com.example.myapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.myapp, PID: 31469
java.lang.NoSuchFieldError: No static field title of type I in class Landroid/support/v7/appcompat/R$id; or its superclasses (declaration of 'android.support.v7.appcompat.R$id' appears in /data/app/com.example.myapp-1/base.apk)
at android.support.v7.internal.view.menu.ListMenuItemView.onFinishInflate(ListMenuItemView.java:89)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:814)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.support.v7.internal.view.menu.MenuPopupHelper$MenuAdapter.getView(MenuPopupHelper.java:370)
at android.support.v7.internal.view.menu.MenuPopupHelper.measureContentWidth(MenuPopupHelper.java:219)
at android.support.v7.internal.view.menu.MenuPopupHelper.tryShow(MenuPopupHelper.java:153)
at android.support.v7.widget.ActionMenuPresenter$OpenOverflowRunnable.run(ActionMenuPresenter.java:752)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Also I am using the last version of appcompat library. I followed tutorials, googled, but nothing is found. What is the reason of this crash? Please, help.
Read here.. http://developer.android.com/guide/topics/ui/menus.html
You have just created menus, you haven't provided their functions. in other words, you just inflate the menus on screen, not provided the function what they will do if use clicks on it.
To enable them you need to implement following method, for example
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
in your mainActivity.
If you are using trasitive = false ; in build.gradle then remove it