one_man
one_man

Reputation: 134

The issue with toolbar and navigation View

I have one activity, inside I have toolbar and navigationView.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.start_page_activity);
    getFragment(new MainFragment());
    mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    mNavigationView = (NavigationView) findViewById(R.id.main_drawer);
    mNavigationView.setNavigationItemSelectedListener(this);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_widget);
    drawerToggle
            = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
    mDrawerLayout.setDrawerListener(drawerToggle);
}
    @Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    Log.i("StartPageActivity", "onPostCreate");
    drawerToggle.syncState();
}

When starting activity at first called Main Fragment. When I select item in NavigationView opens new Fragment. when appear second fragment, inside I use

ActionBar a = ((AppCompatActivity) getActivity()).getSupportActionBar();
    a.setDisplayHomeAsUpEnabled(true);

Up arrow appeared, but when I click on this Up arrow opens NavigationVIEW!!! in fragment inside onOptionsItemSelected I HAVE

case android.R.id.home:{
            Log.i("One", "Dude");
          }

The program does not comply with this code. It does not come to it. I think the problem inside onCreate (activity). Maybe it conflict between ActionBarDrawerToggle, NavigationView and Toolbar.

ADD second fragment

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.reminder_list_fragment, container, false);
    getActivity().setTitle("Fragment1");
    mRecyclerView = (RecyclerView)v. findViewById(R.id.my_recycler_view);
    //{RecyclerAdapter}
    ActionBar a = ((AppCompatActivity) getActivity()).getSupportActionBar();
    a.setDisplayHomeAsUpEnabled(true);
    a.setHomeButtonEnabled(true);
    return v;
}
@Override
public void onResume() {
    super.onResume();
    mRecyclerView.getAdapter().notifyDataSetChanged();
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    inflater.inflate(R.menu.reminder_toolbar, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    Log.d("Testing", "ID == " + id);
    switch (id) {
        case R.id.add_information : {
            Forget f = new Forget();
            ForgetLab.get(getActivity()).addForget(f);
            FragmentManager fm = getFragmentManager();
            Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ReminderFragment.EXTRA_FORGET_ID, f.getId());
            if (mFragment != null) {
                mFragment = new ReminderPagerFragment();
                mFragment.setArguments(bundle);
                fm.beginTransaction().addToBackStack(null)
                        .replace(R.id.fragment_container, mFragment)
                        .commit();
            }
            return true;
        }
        case android.R.id.home:{
            Log.i("One", "Dude");
          }
    }
    return super.onOptionsItemSelected(item);
}

Upvotes: 0

Views: 441

Answers (2)

Mohammad Imran
Mohammad Imran

Reputation: 3273

Use this complete example.

 public abstract class BaseActivity extends AppCompatActivity{
    protected Toolbar toolbar;
    protected User mMe;
    protected DrawerLayout mDrawerLayout;
    protected ActionBarDrawerToggle drawerToggle;

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        mMe = SessionUtils.getUser();
        if (mMe == null) {
            return;
        }
        initToolbar();
        initInstances();

    }

    private void initToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    private void initInstances() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        if (mDrawerLayout != null) {
            final NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
            ImageView profileImage = (ImageView) navigationView.findViewById(R.id.profileImage);
            profileImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityUtils.launchProfileActivity(BaseActivity.this, SessionUtils.getUser());
                }
            });
            TextView name = (TextView) navigationView.findViewById(R.id.name);
            final String fullName = StringUtils.getFullName(mMe.firstName, mMe.lastName);
            name.setText(fullName);
            GlideUtils.load(profileImage, mMe.getImage(), GlideUtils.getCircularFallbackDrawable(this, fullName), new CircleTransformGlide(this));

            navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(MenuItem menuItem) {

                    int itemId = menuItem.getItemId();
                    switch (itemId) {
                        case R.id.messages:
                            ActivityUtils.launchMessagesFragment(BaseActivity.this);
                            LogUtils.LOGD(">>Menu", "Messages");
                            break;
//                        case R.id.notification:
//                            LogUtils.LOGD(">>Menu", "Notification");
//                            break;
                        case R.id.friends:
                            LogUtils.LOGD(">>Menu", "find friends");
                            ActivityUtils.launchFriendsActivity(BaseActivity.this);
                            break;
                        case R.id.termsOfService:
                            ActivityUtils.launchTermsOfServiceFragment(BaseActivity.this);
                            break;
                        case R.id.friendsRrequests:
                            LogUtils.LOGD(">>Menu", "friendsRrequests");
                            ActivityUtils.launchFriendsRequests(BaseActivity.this);
                            break;
                        case R.id.logout:
                            LogUtils.LOGD(">>Menu", "Logout");
                            DialogUtils.LogoutConfirmDialogFragment logoutConfirmDialogFragment = new DialogUtils.LogoutConfirmDialogFragment();
                            logoutConfirmDialogFragment.show(getSupportFragmentManager(), "Logout Confirmation Fragment");
//                            LoginManager.reset(BaseActivity.this);
                            break;
                    }
//                    menuItem.setChecked(true);
//                    if (R.id.friends == itemId) {
//                        mDrawerLayout.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                mDrawerLayout.closeDrawers();
//                            }
//                        }, 1000);
//                    } else {
//                        mDrawerLayout.closeDrawers();
//                    }
                    return true;
                }
            });
            drawerToggle = new DrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name, new DrawerToggleListener() {
                @Override
                public void OnDrawerClose() {

                }

                @Override
                public void OnDrawerOpen() {

                }
            });
            mDrawerLayout.setDrawerListener(drawerToggle);


            final ActionBar supportActionBar = getSupportActionBar();
            if (supportActionBar != null) {
                supportActionBar.setHomeButtonEnabled(true);
                supportActionBar.setDisplayHomeAsUpEnabled(true);
            }
        }
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if (drawerToggle != null)
            drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (drawerToggle != null)
            drawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return (drawerToggle != null && drawerToggle.onOptionsItemSelected(item)) || super.onOptionsItemSelected(item);

    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    private static class DrawerToggle extends ActionBarDrawerToggle {
        DrawerToggleListener mToggleListener;

        public DrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes, DrawerToggleListener toggleListener) {
            super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
            mToggleListener = toggleListener;
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            mToggleListener.OnDrawerClose();
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            mToggleListener.OnDrawerOpen();
        }
    }

    private static abstract class DrawerToggleListener {
        public abstract void OnDrawerClose();

        public abstract void OnDrawerOpen();
    }

}

You Main activity must extends BaseActivity

public class MainActivity extends BaseActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (!LoginManager.isFirstFlowFinished(this)) {
        LoginManager.launchCurrentFragment(this);
        finish();
        return;
    }
    Intent intent = getIntent();
    handleIntent(intent);
    setContentView(R.layout.activity_main_new);
    LogUtils.LOGD(">>Intent", "onCreate");
}

@Override
public void onResume() {
    super.onResume();
    LocationTracker.promptIfNeededForEnableLocation(this);
    CommonUtils.checkIfPlayServicesNeedToUpdate(this);
    AppEventsLogger.activateApp(this);
}

@Override
protected void onPause() {
    super.onPause();
    AppEventsLogger.deactivateApp(this);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_search, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_search_icon:
            ActivityUtils.launchSearchActivity(this);
            break;
    }
    return true;
}

@Override
public void onBackPressed() {
    super.onBackPressed();
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    LogUtils.LOGD(">>Intent", "on handle Intent");
    handleIntent(intent);
}

}

And here is activity_main_new.xml

<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/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">

<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:minHeight="?actionBarSize"
        android:background="?colorPrimary"
        app:layout_collapseMode="pin"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >
        <TextView
            android:textColor="@color/white"
            android:textSize="18sp"
            android:textStyle="bold"
            android:text="Friends Locator"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        </android.support.v7.widget.Toolbar>

    <fragment
        android:orientation="vertical"
        android:id="@+id/viewPager"
        android:name="com.macrotechnologies.friendslocator.ui.NearBySuggestionsFragment"
        android:tag="com.macrotechnologies.friendslocator.ui.NearBySuggestionsFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/navigation"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/nav_header"

    app:itemIconTint="@color/nav_item_icon_tint_color"
    app:itemTextColor="@color/nav_item_text_color"
    app:menu="@menu/navigation_drawer_items" />

and Navigation Menu item is as:

<?xml version="1.0" encoding="utf-8"?>

<group android:checkableBehavior="none">

    <item
        android:id="@+id/friends"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/friends_caps" />
    <item
        android:id="@+id/messages"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/messages" />
    <item
        android:id="@+id/friendsRrequests"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/friendsRequests" />
   <!-- <item
        android:id="@+id/notification"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/notifications" />-->

    <!--<item-->
        <!--android:id="@+id/about"-->
        <!--android:icon="@drawable/ic_navigation_chevron_right"-->
        <!--android:title="@string/about" />-->
    <item
        android:id="@+id/termsOfService"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/terms_of_service" />

    <item
        android:id="@+id/logout"
        android:icon="@drawable/ic_navigation_chevron_right"
        android:title="@string/log_out" />
</group>

Upvotes: 1

Arjun Gurung
Arjun Gurung

Reputation: 431

You should overRide onOptionsItemSelected(MenuItem item) and setHasOptionsMenu(true) should be called inside onCreate(Bundle savedInstanceState)

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(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 == android.R.id.home) {
        getActivity().onBackPressed();
    }

    return super.onOptionsItemSelected(item);
}  I hope this works....

Upvotes: 3

Related Questions