Navigation drawer: How do I set the navigation item selected listener with custom tool bar? - android

I don't see any error when I open the navigation drawer, but it keeps getting closed whenever I select an item. Edit: My drawer gets closed automatically on item selection without showing the Toast message as mentioned in NavigationItemSelectedListener. The toast message is not displayed.
I have used a custom toolbar in which I have added an image view as a side menu button.
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CustomToolbar"
android:id="#+id/drawer_layout">
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/header_file"
app:menu="#menu/main_manu"
android:layout_gravity="start"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bggradient">
<include
android:id="#+id/toolbar"
layout="#layout/layout_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.drawerlayout.widget.DrawerLayout>
public class CustomToolbar extends AppCompatActivity {
private Toolbar toolbar;
private DrawerLayout drawer;
private NavigationView navigationView;
private ActionBarDrawerToggle toggle;
private ImageView side_menu;
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_toolbar);
toolbar = (Toolbar) findViewById(R.id.navigation_bar);
side_menu = findViewById(R.id.side_menu);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigation_view);
setSupportActionBar(toolbar);
toggle = new ActionBarDrawerToggle(this, drawer, R.string.open, R.string.close);
drawer.addDrawerListener(toggle);
toggle.syncState();
side_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawer.openDrawer(Gravity.LEFT);
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home_menu: {
Toast.makeText(CustomToolbar.this, "Home Selected", Toast.LENGTH_SHORT).show();
}
case R.id.community_menu: {
Toast.makeText(CustomToolbar.this, "Community Selected", Toast.LENGTH_SHORT).show();
}
case R.id.posts_menu: {
Toast.makeText(CustomToolbar.this, "Posts Selected", Toast.LENGTH_SHORT).show();
}
case R.id.website_menu: {
Toast.makeText(CustomToolbar.this, "Website Selected", Toast.LENGTH_SHORT).show();
}
case R.id.share_menu: {
Toast.makeText(CustomToolbar.this, "Share Selected", Toast.LENGTH_SHORT).show();
}
case R.id.feedback_menu: {
Toast.makeText(CustomToolbar.this, "Feedback Selected", Toast.LENGTH_SHORT).show();
}
case R.id.about_menu: {
Toast.makeText(CustomToolbar.this, "About us Selected", Toast.LENGTH_SHORT).show();
}
case R.id.logout_menu: {
Toast.makeText(CustomToolbar.this, "Logout Selected", Toast.LENGTH_SHORT).show();
}
}
return false;
}
});
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
I have tried other method with default toolbar, and it was working properly but I am not able to figur out the problem with custom toolbar. I wanted to display a toast on item selection inside the navigation drawer. Please help me find the solution...
Thank you.

In onNavigationItemSelected, Change this
return false;
to
return true;

After so long finally I found the solution to my problem. But I don't know why it was happening like that but I'm happy that it is finally working. And I am also very happy to share it with those who may experience the same issue in the future which I hope they won't.
I referred to the link from the Git hub for this solution. Link: https://github.com/priyalbhatewara123/Navigation-Drawer--Android
Finally here is the solution I found,
I just added the following lines of codes below </ScrollView> which was above <ScrollView> in the problematic code used in my activity_custom_toolbar.xml.
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/header_file"
app:menu="#menu/main_manu"
android:layout_gravity="start"/>
I'm also adding the code after changes,
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CustomToolbar"
android:id="#+id/drawer_layout">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bggradient">
<include
android:id="#+id/toolbar"
layout="#layout/layout_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/header_file"
app:menu="#menu/main_manu"
android:layout_gravity="start"/>
</androidx.drawerlayout.widget.DrawerLayout>

Related

How to move to another activity using bottom navigation bar using kotlin in android studio? [duplicate]

//Here is my java code
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
BottomNavigationView bottomNavigationView;
NavigationView navigationView;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull final MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
HomeFragment homeFragment=new HomeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout,homeFragment).commit();
return true;
case R.id.navigation_stylist:
StylistFragment stylistsFragment=new StylistFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction1=getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.frameLayout,stylistsFragment).commit();
return true;
case R.id.navigation_apps:
MyapptsFragment myaaptsFragment=new MyapptsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction2=getSupportFragmentManager().beginTransaction();
fragmentTransaction2.replace(R.id.frameLayout,myaaptsFragment).commit();
return true;
case R.id.navigation_tips:
HairtipsFragment hairtipsFragment=new HairtipsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction3=getSupportFragmentManager().beginTransaction();
fragmentTransaction3.replace(R.id.frameLayout,hairtipsFragment).commit();
return true;
case R.id.navigation_account:
AccountFragment accountFragment=new AccountFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction4=getSupportFragmentManager().beginTransaction();
fragmentTransaction4.replace(R.id.frameLayout,accountFragment).commit();
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//start onboarding when app is opening first time
isUserFirstTime = Boolean.valueOf(Utils.readSharedSetting(HomeActivity.this, PREF_USER_FIRST_TIME, "true"));
Intent introIntent = new Intent(HomeActivity.this, OnboardingActivity.class);
introIntent.putExtra(PREF_USER_FIRST_TIME, isUserFirstTime);
if (isUserFirstTime)
startActivity(introIntent);
setContentView(R.layout.activity_home);
bottomNavigationView = findViewById(R.id.bottom_navigation);
navigationView=findViewById(R.id.nav_drawer);
//bottom navigationview listener
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
//navigation drawer listener
navigationView.setNavigationItemSelectedListener(this);
//open home fragment on first launch
HomeFragment homeFragment=new HomeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout,homeFragment).commit();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
HomeFragment homeFragment=new HomeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout,homeFragment).commit();
return true;
case R.id.nav_products:
StylistFragment stylistsFragment=new StylistFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction1=getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.frameLayout,stylistsFragment).commit();
return true;
case R.id.nav_promotions:
MyapptsFragment myaaptsFragment=new MyapptsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction2=getSupportFragmentManager().beginTransaction();
fragmentTransaction2.replace(R.id.frameLayout,myaaptsFragment).commit();
return true;
case R.id.nav_purchases:
HairtipsFragment hairtipsFragment=new HairtipsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction3=getSupportFragmentManager().beginTransaction();
fragmentTransaction3.replace(R.id.frameLayout,hairtipsFragment).commit();
return true;
case R.id.nav_settings:
AccountFragment accountFragment=new AccountFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction4=getSupportFragmentManager().beginTransaction();
fragmentTransaction4.replace(R.id.frameLayout,accountFragment).commit();
return true;
}
return false;
}
}
// Here is my 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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.NavigationView
android:id="#+id/nav_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:theme="#style/menu_text_style"
app:menu="#menu/navigation_drawer" />
<!--app:headerLayout="#layout/nav_header_main"-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/shadow"
android:animateLayoutChanges="true">
</FrameLayout>
<View
android:id="#+id/shadow"
android:layout_width="match_parent"
android:layout_height="#dimen/_1sdp"
android:layout_above="#id/bottom_navigation"
android:background="#color/shadow"/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemIconTint="#color/navigationitem"
app:itemTextColor="#color/navigationitem"
app:menu="#menu/navigation_item"/>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
I want to create both navigation drawer and bottom navigation in the same activity. I created XML design now I have to write java code for both. Bottom navigation is working perfectly but navigation item clicklistener is not working. I created fragments for navigation drawer and also for bottom navigation. When I click the items in navigation drawer it's not redirecting to respective fragment. The given clicklistener for navigation drawer is not at all working.
Solution:
Try the following steps to get it working:
Step1: Implement onNavigationItemSelected as shown below:
.... extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Step2: Use the method generated by the interface as:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.your_drawer_item_id:
....
....
case R.id.your_drawer_item_id:
....
....
}
}
Step3: In your class declare a Global variable:
public NavigationView navigationView;
Step4: In your onCreate() initialize the variable as:
navigationView = (NavigationView) findViewById(R.id.your_nav_view);
Finally: Setup the navigationView:
navigationView.setNavigationItemSelectedListener(this);
That's it.
Hope it works.
DrawerLayout 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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_vendor_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_drawer_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/White"
android:fitsSystemWindows="true"
app:itemBackground="#android:color/white"
app:itemIconTint="#color/bottom_color"
app:itemTextColor="#color/bottom_color"
app:headerLayout="#layout/nav_header_vendor_drawer_layout"
app:menu="#menu/vendor_drawer_menu" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
app_bar_vendor_drawer_layout xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context="logixtic.android.web.vd.driver.activities.DriverDrawerActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/MyMaterialTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/Project_Standard"
app:popupTheme="#style/MyMaterialTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:layout_above="#+id/bottom_navigation">
</FrameLayout>
<View
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="#drawable/toolbar_dropshadow_above"
android:layout_above="#id/bottom_navigation"/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="#color/White"
app:itemIconTint="#color/bottom_color"
app:itemTextColor="#color/bottom_color"
app:menu="#menu/vendor_bottom_navigation"/>
</RelativeLayout>
Try it.
You can use on the same activity using a method that recive a MenuItem parameter like this:
private void myClickItem(MenuItem item){
switch (item.getItemId()) {
case R.id.bottom_home:
// DO SOMETHING
break;
case R.id.drawer_main:
// DO SOMETHING
break;
}
}
Then, call like this:
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(item -> { // using lamda
myClickItem(item); //call here
return true;
});
NavigationView navigationView = findViewById(R.id.nv);
navigationView.setNavigationItemSelectedListener(item -> {
myClickItem(item); // call the same method here
drawerLayout.closeDrawers(); // bonus: hide navigation after click
return false;
});
You don't need to modify your xml res, it'll work fine.

How to add a back button to action bar / toolbar

I have written a piece of code as part of an app where I want to implement a back button on the action bar/tool bar such that when the button is pressed, the previous page (the page/fragment immediately before the current page/fragment) will be displayed.
This is the code for the ToolBar, DrawerLayout, NavigationView and getSupportActionBar():
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setVisibility(View.VISIBLE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
I am unable to use ActionBar. For some reason (I don't know why), my Android studio/ program, will not allow me to use the ActionBar. So I am substituting that with the set/getSupportActionBar().
The function used in relation to this are:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_settings, 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();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
My activity_main.xml file is:
<?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:fitsSystemWindows="true"
android:id="#+id/activity_main"
android:orientation="vertical"
tools:openDrawer="start"
tools:context="com.example.albin.settings_menu.SettingsActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="Settings"/>
<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">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar">
</FrameLayout>
<android.support.design.widget.NavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:layout_marginTop="-24dp"
app:menu="#menu/options_menu" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
</LinearLayout>
The problem is that I don't know which is the useful code, which is the useless code and how to mix/join/(add additional codes to) these (codes, methods, variables/objects, fragments, xml layouts) to get the desired outcome, that is, the application of a back button on the action bar/tool bar.
Most of the code above is implemented for the up button, not the back button. I have read at several places that up and back buttons are not the same.
I tried several links on internet as well as on this site, but none of them has just what I need.
Hope someone can give me an clear answer...
You can include the back icon in ToolBar:
Initialize ToolBar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
You can use an drawable icon as a back button.
toolbar.setNavigationIcon(R.drawable.your_drawable_icon);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// what do you want here
}
});
If you do not want to use drawable icon then:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// what do you want here
}
});
Actually your layout having that issue because you have added toolbar in RelativeLayout so drawer layout is overlapping on it that's why you would not able to click on back arrow, i have fix your layout see below
<?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"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:navigationIcon="#drawable/ic_back_black"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="Settings" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/options_menu" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
The simplest way would be to add parent activity in manifest file as developer docs suggest.
<activity
android:name=".ChildActivity"
android:parentActivityName=".ParentActivity" >
and java code you already have done it, setSupportActionbar and setHomeAsUpEnabled.
Edited :
its necessary to add up action for icon to be visible, as mentioned in
Android Developer Docs
So toolbar gives added flexibility to modify title-bar in Android.
As far as why getActionBar is not working and you are compelled to use getSupportActionBar is because you must be using SupportLibrary. SupportLibrary gives backward compatibility to earlier SDK versions.
If you want to modify your title-bar/header/action-bar extensively
then use toolbar otherwise use action-bar.
Add a navigation click listener to your toolbar , like below
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
If you are referencing some actions from the action bar, such as a Save action or a Share one, and you are overriding onOptionsItemSelected method, then you need to define the behavior when the back or home button is clicked:
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
//save stuff
break;
//this is what you need to add to reference again back/home button
case android.R.id.home:
//do your stuff here, usually back to the home or close the current activity
getActivity().finish();
break;
default:
break;
}
return true;

PreferenceActivity with Navigation Drawer Throws Null Pointer Exception

I had a PreferenceActivity which was working fine. Then, I decided to add a navigation drawer to it, and edited the layouts according to my other activity layouts which also have working navigation drawers. However, after doing that, my PreferenceActivity stopped opening and started throwing a NPE on start. I can't even open that activity anymore. Problem is in onCreate, obviously, and also in an onClick method as stated in the logcat. Yet, there are two onClick's in this activities onCreate, and I'm not seeing how those result in a NPE, since they are the exact same in my other working activities. My layout xmls are seperated into 3 xmls according to the default DrawerLayout implementation. Without further due, here are the codes and xmls:
PreferenceActivity:
public class FirstYearCoursesActivity extends PreferenceActivity
implements NavigationView.OnNavigationItemSelectedListener {
private AppCompatDelegate mDelegate;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_year_courses);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar((toolbar));
Window window = this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark));
addPreferencesFromResource(R.xml.prefs);
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_view2);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
ImageButton logoutButton = (ImageButton) headerView.findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(FirstYearCoursesActivity.this, LoginActivity.class);
startActivity(intent);
}
});
}
#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
protected void onPause() {
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final Handler handler = new Handler();
if (drawer.isDrawerOpen(GravityCompat.START)) {
handler.postDelayed(new Runnable() {
#Override
public void run() {
drawer.closeDrawer(GravityCompat.START);
}
}, 200);
super.onPause();
} else {
super.onPause();
}
}
private void setSupportActionBar(#Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
private AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, null);
}
return mDelegate;
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
String key = preference.getKey();
switch (key) {
case "math119":
Intent intent = new Intent(FirstYearCoursesActivity.this, Math119Activity.class);
startActivity(intent);
break;
default:
Toast.makeText(this, "Other Click", Toast.LENGTH_SHORT).show();
break;
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// to be filled
int id = item.getItemId();
if (id == R.id.nav_camera) {
} else if (id == R.id.nav_gallery) {
} 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) {
}
return true;
}
}
activity.xml:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<include
layout="#layout/app_bar_first_year_courses"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view2"
android:layout_width="250dp"
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:background="#ffffffff"
app:itemTextColor="#000000"
app:itemTextAppearance="#style/TextAppearance.AppCompat.Body1"/>
</android.support.v4.widget.DrawerLayout>
app_bar.xml:
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".activities.FirstYearCoursesActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_first_year_courses"/>
</android.support.design.widget.CoordinatorLayout>
content.xml:
<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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".activities.FirstYearCoursesActivity"
tools:showIn="#layout/app_bar_first_year_courses"
android:orientation="vertical">
</LinearLayout>
nav_header.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="140dp"
android:background="#drawable/profilebanner"
android:gravity="bottom"
android:orientation="vertical"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:id="#+id/header">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/logoutButton"
android:src="#drawable/ic_power_settings_new_white_18dp"
android:background="#00ffffff"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="30dp"
android:layout_marginRight="10dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/headerClick"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:paddingTop="20dp">
<ImageView
android:layout_width="65dp"
android:layout_height="65dp"
android:id="#+id/imageView"
android:background="#drawable/onur"
android:layout_centerVertical="true"
android:layout_alignParentStart="false"
android:layout_alignBottom="#+id/textView3"
android:layout_marginBottom="-20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Onur Çevik"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:id="#+id/textView2"
android:textSize="13sp"
android:layout_toRightOf="#+id/imageView"
android:layout_marginLeft="25dp"
android:layout_marginTop="45dp"/>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Environmental Engineering"
android:textSize="11sp"
android:layout_toRightOf="#+id/imageView"
android:layout_marginLeft="25dp"
android:layout_below="#+id/textView2"
android:layout_alignParentStart="false"/>
</RelativeLayout>
</RelativeLayout>
prefs.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="firstyearprefs">
<Preference
android:title="Math-119"
android:key="math119"/>
<Preference
android:title="Math-120"
android:key="math120"/>
<Preference
android:title="Phys-105"
android:key="phys105"/>
<Preference
android:title="Phys-106"
android:key="phys106"/>
<Preference
android:title="Chem-107"
android:key="chem107"/>
<Preference
android:title="Eng-101"
android:key="eng101"/>
<Preference
android:title="Eng-102"
android:key="eng102"/>
<Preference
android:title="Ce-101"
android:key="ce101"/>
</PreferenceScreen>
logcat:
02-08 02:10:35.415 30815-30815/com.theoc.proto E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.theoc.proto, PID: 30815
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at android.preference.PreferenceScreen.bind(PreferenceScreen.java:143)
at android.preference.PreferenceActivity.bindPreferences(PreferenceActivity.java:1419)
at android.preference.PreferenceActivity.access$000(PreferenceActivity.java:123)
at android.preference.PreferenceActivity$1.handleMessage(PreferenceActivity.java:230)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
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:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
EDIT:
One thing worth mentioning is that I triple checked the activity and it's adapter that leads to this PreferenceActivity on list item click. I reversed all my Drawer Layout implementations, and I was able to open this PreferenceActivity through parent activity. Navigation Drawer code, or layouts are the ones messing with it. I'm getting the listview.onclick(adapter) NPE because my list item click on parent activity goes to a null reference, which in this case it the PreferenceActivity itself. Also debug didn't show me anything null in PreferenceActivity's onCreate, except savedInstanceState.
I was able to reproduce the same NPE using your code and fixed it by replacing the addPreferencesFromResource call (note that it's deprecated) using a fragment instead as described in these threads:
Android: Preference Fragment with a Navigation Drawer's Fragment
What to use instead of "addPreferencesFromResource" in a PreferenceActivity?
Although, on my version, the preferences view overlaps the toolbar and I am not sure what the activity layout should be to fix that, maybe it will be OK in yours.

NavigationView on both side

I need to open navigation view on both side with different menu.. Also I need to change navigation icon (Currently with three horizontal line). This is better if I can open the nav_view and na_view2 with separate button clicks, these buttons are available in my toolbar, or I need to know how can I set separate icons on both side?.
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<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.NavigationView
android:id="#+id/nav_view2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer1" />
</android.support.v4.widget.DrawerLayout>
Any help will be highly appreciable.
We can get buttons from toolbar by following lines,
Button btnStart = (Button) findViewById(R.id.btnStart);
Button btnEnd = (Button) findViewById(R.id.btnEnd);
and while click the start button we can open and hide left drawer by following listener,
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else drawer.openDrawer(GravityCompat.START);
}
});
and while click the end button we can open and hide right drawer by following listener,
btnEnd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(GravityCompat.END))
drawer.closeDrawer(GravityCompat.END);
else drawer.openDrawer(GravityCompat.END);
}
});
And our onBackPressed method will be
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
super.onBackPressed();
}
}
This also used to close the drawers if those is in open state.

How to catch navigation icon click on toolbar from fragment?

I have a dialog fragment in which I have toolbar in layout.
I want to make back button(Navigation Icon) working in toolbar and exit the fragment when clicked. But I am unable to catch the click event on the toolbar's navigation icon in the (dialog)fragment.
Here is how I am getting toolbar :
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
toolbar.setTitle(itemType);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
Here is my layout file for the dialog fragment :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/panel_cyan"
android:id="#+id/rootLayout"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#color/color_primary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listViewItems"
/>
</RelativeLayout>
**Here is what is have tried so far but failed **
Options item click in id R.id.home
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
setNavigationOnClick() on the toolbar :
toolbar.setNavigationOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Back clicked!", Toast.LENGTH_SHORT).show();
}
});
add code block toolbar.setNavigationOnClickListener after setSupportActionBar(toolbar)
This works for me.
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"your icon was clicked",Toast.LENGTH_SHORT).show();
}
});
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// do what ever you want here
}
return true;
}
});
Probably important as well: If you use Databinding like
MyPojoBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setPojo(myPojo)
the setSupportActionBar(toolbar) (followed by setting a click listener, title, or other toolbar attributes) must come AFTER the initialization of the binding.

Categories

Resources