How to open links from menu.xml using Fragments - android

I'm trying to add clickable items from menu.xml. It just not working, even Toast effect.
Layout is copy/paste below so you can check it.
There is my MainActivity.java when Im trying using id's.
MainActivity:
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private SectionsPagerAdapter mSectionsPagerAdapter;
private static final String TAG = "MainActivity";
private ViewPager mViewPager;
ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.hamburgermenu);
DrawerLayout drawerLayout = findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
tabLayout.getTabAt(0).setText("Home").setIcon(R.drawable.homeicon);
tabLayout.getTabAt(1).setText("Section 1").setIcon(R.drawable.explorer);
tabLayout.getTabAt(2).setText("Section 2").setIcon(R.drawable.innovator);
tabLayout.getTabAt(3).setText("Section 3").setIcon(R.drawable.collar);
tabLayout.setTabTextColors(getResources().getColorStateList(R.color.white));
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.dashboard:
Intent intentExplorer = new Intent(this, Tab1Explorer.class);
startActivity(intentExplorer);
break;
case R.id.action_search:
//Display Toast for test
Log.d(TAG,"test");
Toast.makeText(this,"Search!", Toast.LENGTH_SHORT).show();
break;
case R.id.action_help:
Intent intentContact = new Intent(this,Tab3Collar.class);
startActivity(intentContact);
break;
case R.id.action_about:
Toast.makeText(this,"This is simple About Demo", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(this,"XYZ", Toast.LENGTH_LONG).show();
return super.onOptionsItemSelected(item);
}
Toast.makeText(this,"XYZ", Toast.LENGTH_LONG).show();
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
Tab0Home tab0 = new Tab0Home();
return tab0;
case 1:
Tab1Section tab1 = new Tab1Section();
return tab1;
case 2:
Tab2Section tab2 = new Tab2Section();
return tab2;
case 3:
Tab3Section tab3 = new Tab3Section();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
// Show 4 total pages.
return 4 ;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Home";
case 1:
return "Section11";
case 2:
return "Section22";
case 3:
return "Section33";
}
return null;
}
}
}
menu_main.xml file looks fine. I have android:id's, icons, titles...
Activity_main.xml file looks:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:title="#string/app_name"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextAppearance="#style/CustomTextStyle">
<android.support.design.widget.TabItem
android:id="#+id/tabItem0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_0" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_1" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_2" />
<android.support.design.widget.TabItem
android:id="#+id/tabItem3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tab_text_3" />
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start">
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/white"
app:menu="#menu/menu_main">
</android.support.design.widget.NavigationView>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
I just want to display for example Toast when I click "Search" from Menu, but it not working. It just colapse hamburger menu without effect.
What should I change?

The navigation view does not use the onOptionsItemSelected method, instead you need to call navigationView.setOnNavigationItemSelectedListener

Related

Android: Navigation Drawer with fragment and activities?

I'm trying to do navigation drawer with 2 fragment(later i will add), and 4 activities. In my code when i call activity and close. It's very laggy. I want it very smooth. Please see my code.
ublic class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private NavigationView navigationView;
FragmentManager fragmentManager;
private String[] pageTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pageTitle = new String[]{getString(R.string.frag_home),
getString(R.string.nav_introduction),};
drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle(pageTitle[0]);
setSupportActionBar(toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView)findViewById(R.id.nav_view);
// assert navigationView != null: Log.wtf("haha", "OMG");
assert navigationView != null;
navigationView.setNavigationItemSelectedListener(this);
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, new Fragment_home()).commit();
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.nav_introduction: {
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, new Fragment_Introduction()).commit();
}
break;
case R.id.nav_settings: {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
} break;
case R.id.nav_feedback: {
Intent intent = new Intent(MainActivity.this, FeedbackActivity.class);
startActivity(intent);
}
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
assert drawerLayout != null;
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
public void onClickHome(View view){
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, new Fragment_home()).commit();
}
public void onClickFilter(View view){
Intent intent = new Intent(MainActivity.this, FIlterActivity.class);
startActivity(intent);
}
}
And my main activity code is following:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
app:titleTextColor="#android:color/white" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="right">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4">
</LinearLayout>
<TextView
android:text=""
android:layout_width="0dp"
android:layout_height="match_parent"
android:textColor="#android:color/white"
android:gravity="right|center"
android:layout_weight="1"
android:onClick="onClickHome"/>
<ImageView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_marginRight="3dp"
android:gravity="center"
android:src="#drawable/filter_icon"
android:onClick="onClickFilter"
/>
</LinearLayout>
</android.support.v7.widget.Toolbar>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<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/drawer_menu" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
It's like when i use Activity and Fragment it's very laggy. Is there other way to do smooth?
Solution: I used handler. But it's not best.
case R.id.nav_settings: {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
}
}, 250);
} break;

java.lang.ArrayIndexOutOfBoundsException: length=5; index=5? I want to add fragment in navigation drawer

I am getting error,When I click LoginFragment.When I remove loginFragment.
It works fine.
How to change length for adding more fragment.I am not able to add new fragment.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG_HOME = "home";
private static final String TAG_PHOTOS = "photos";
private static final String TAG_MOVIES = "movies";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
private static final String TAG_LOGIN = "login";
public static int navItemIndex = 0;
public static String CURRENT_TAG = TAG_HOME;
private NavigationView navigationView;
private DrawerLayout drawer;
private Toolbar toolbar;
private String[] activityTitles;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
// Navigation view header
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// load nav menu header data
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
// photos
PhotosFragment photosFragment = new PhotosFragment();
return photosFragment;
case 2:
// movies fragment
MoviesFragment moviesFragment = new MoviesFragment();
return moviesFragment;
case 3:
// notifications fragment
NotificationsFragment notificationsFragment = new NotificationsFragment();
return notificationsFragment;
case 4:
// settings fragment
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
case 5:
// ic_login_black_24dp fragment
LoginFragment loginFragment = new LoginFragment();
return loginFragment;
default:
return new HomeFragment();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
//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) {
//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.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_photos:
navItemIndex = 1;
CURRENT_TAG = TAG_PHOTOS;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_notifications:
navItemIndex = 3;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_login:
navItemIndex = 5;
CURRENT_TAG = TAG_LOGIN;
break;
default:
navItemIndex = 0;
}
//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);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, 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
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
}
activity_main_drawer.xml
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/nav_home" />
<item
android:id="#+id/nav_photos"
android:icon="#drawable/ic_photo_library_black_24dp"
android:title="#string/nav_photos" />
<item
android:id="#+id/nav_movies"
android:icon="#drawable/ic_local_movies_black_24dp"
android:title="#string/nav_movies" />
<item
android:id="#+id/nav_notifications"
android:icon="#drawable/ic_notifications_black_24dp"
android:title="#string/nav_notifications" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_settings_black_24dp"
android:title="#string/nav_settings" />
<item
android:id="#+id/nav_login"
android:icon="#drawable/ic_login_black_24dp"
android:title="login" />
</group>
activity_main.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/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.v4.widget.DrawerLayout>
app_bar_main.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="info.androidhive.navigationdrawer.activity.MainActivity">
<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>
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
nav_header_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/view_container"
android:layout_width="match_parent"
android:layout_height="#dimen/nav_header_height"
android:gravity="bottom"
android:orientation="vertical"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/img_header_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#mipmap/ic_launcher" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<ImageView
android:id="#+id/img_profile"
android:layout_width="#dimen/profile_width"
android:layout_height="#dimen/profile_height"
android:paddingTop="#dimen/nav_header_vertical_spacing"
app:srcCompat="#android:drawable/sym_def_app_icon" />
<TextView
android:id="#+id/namea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/website"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5?
Looks like Exception happens when you call:
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
navItemIndex has range from 0 to 5 (a.e. length 6) when activityTitles has only 5 items
Solution:
Set 6 items for activityTitles

Navigation Item Selected State through Multiple Activities

I have a working Navigation Drawer through out multiple activities and I am looking to highlight the current Navigation Item Selected after it changes the activity. How can I save the Item Selected Listener through out the whole app while the onCreateDrawer its recreating itself on every other activity?
If you need any other relevant activity or have any feedback, dont hesitate to indulge me!
BaseActivity
public class BaseActivity extends AppCompatActivity {
public NavigationView mNavigationView;
protected ActionBarDrawerToggle mToggle;
protected Toolbar mToolbar;
public DrawerLayout mDrawerLayout;
protected void onCreateDrawer() {
//Instantiate Navigation Drawer
setupNavDrawer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logout) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mToggle.onConfigurationChanged(newConfig);
}
//Set up Navigation Drawer
private void setupNavDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mNavigationView= (NavigationView) findViewById(R.id.navigation_view);
setSupportActionBar(mToolbar);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.setDrawerListener(mToggle);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull final MenuItem item) {
mDrawerLayout.closeDrawers();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (item.getItemId()){
case R.id.nav_home:
Intent intent0 = new Intent(BaseActivity.this, Home.class);
startActivity(intent0.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
mNavigationView.setCheckedItem(R.id.nav_home);
break;
case R.id.nav_settings:
Intent intent1 = new Intent(BaseActivity.this, Settings.class);
startActivity(intent1.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
mNavigationView.setCheckedItem(R.id.nav_settings);
break;
case R.id.nav_selection:
Intent intent2 = new Intent(BaseActivity.this, Selection.class);
startActivity(intent2.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
mNavigationView.setCheckedItem(R.id.nav_selection);
break;
case R.id.nav_privacy_policy:
Intent intent3 = new Intent(BaseActivity.this, PrivacyPolicy.class);
startActivity(intent3.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
mNavigationView.setCheckedItem(R.id.nav_privacy_policy);
break;
default:
Intent intent4 = new Intent(BaseActivity.this, Home.class);
startActivity(intent4.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));
mNavigationView.setCheckedItem(R.id.nav_home);
break;
}
}
}, 225);
return true;
}
});
}
}
Home
public class Home extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
super.onCreateDrawer();
}
Selection
public class Selection extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection);
super.onCreateDrawer();
}
Activity_Home.XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/layout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" >
<TextView
android:text="Hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#FFFF"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu"/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Activity_Selection.XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/layout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.app.navigationdrawer.Teste">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" >
<TextView android:text="Selection" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewTeste" />
</RelativeLayout>
<!-- <include layout="#layout/toolbar_actionbar" /> -->
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#FFFF"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu"/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
Once I also had similar problem. And here is what worked for me:
Change menu ids and class names as per your situation.
private void setupNavDrawer() {
// ...
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.mainSection:
drawerLayout.closeDrawers();
startNewActivity(MainActivity.class);
break;
case R.id.allGames:
drawerLayout.closeDrawers();
startNewActivity(GamesActivity.class);
break;
return true;
}
});
setNavigationViewCheckedItem();
// .....
}
And here setNavigationViewCheckedItem mehod:
private void setNavigationViewCheckedItem() {
if (this.getClass().equals(MainActivity.class)) {
navigationView.setCheckedItem(R.id.mainSection);
} else if (this.getClass().equals(GamesActivity.class)) {
navigationView.setCheckedItem(R.id.allGames);
}
}

android toolbar with fragments

I have toolbar and framelayout(for fragments) in my main activity layout. I have to show the toolbar in every fragments. But the issue is each fragment has different background image that is dynamically changing. Toolbar menu icon is used for navigation drawer open and close operation. How I will handle these issue?
Before posting the code block let's first understand what are we are going to do.
1.Create a HomeActivity that holds all the fragments.
Here is the activity_home.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_home"
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_home"
app:menu="#menu/activity_home_drawer" />
</android.support.v4.widget.DrawerLayout>
Here is the app_bar_home.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
the other xmls of navigationview -- activity_home_drawer.xml contains navigation drawer contents and nav_header_home.xml is the navigation drawer header layout.
2.Let's come to java part of the HomeActivity.java
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private HomeBean bean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ButterKnife.bind(this);
initListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//this menu contains all the common menu item actions
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
//common options bar item click here i have notifications icon common for all the fragments
#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.
switch (item.getItemId()){
case R.id.action_notifications:
AppUtils.launchActivity(HomeActivity.this, NotificationActivity.class,intentData);
return false;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.nav_dashboard:
//you can cache this fragment in case of repeated creations
selectedFragment = new DashBoardFragment();
}
break;
}
if(selectedFragment != null){
displayFragment(selectedFragment);
DrawerLayout drawer = ButterKnife.findById(this,R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
return true;
}
private void displayFragment(Fragment fragment) {
if(fragment !=null){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
}
#Override
public void initToolBar() {}
public void setToolbar(Toolbar toolbar){
setSupportActionBar(toolbar);
setActionBarToggle(toolbar);
}
private void setActionBarToggle(Toolbar toolbar) {
DrawerLayout drawer = ButterKnife.findById(this, 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();
}
#Override
public void initListener() {
NavigationView navigationView = ButterKnife.findById(this,R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//as the first item is show by default
navigationView.getMenu().getItem(0).setChecked(true);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
Now as an example let see how the fragments are written.
public class SettingsFragment extends Fragment {
#BindView(R.id.toolbar)
Toolbar toolbar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings,container,false);
ButterKnife.bind(this,view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
((HomeActivity)getActivity()).setToolbar(toolbar);
}
}
Corresponding fragment xml fragment_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<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="Fragment Name">
<android.support.design.widget.AppBarLayout
android:id="#+id/notification_appbar"
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"
app:title="#string/settings"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_settings" />
</android.support.design.widget.CoordinatorLayout>
the corresponding xml content_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/min_widget_padding"
android:id="#+id/nsv_settings_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
// your content goes here
</<android.support.v4.widget.NestedScrollView>
I hope this gives clear picture on how to do in case if you have any other doubts please comment.
Use this code. I helped
public class MyFragment extends Fragment {
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);// To enable actionbar in fragments
super.onCreate(savedInstanceState);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//Here it is necessary to connect the layout menu
inflater.inflate(R.menu.fragment2, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}

How to set Click NavigationItem menu in Android

I want use NavidationDrawer for application menu, but when click on NavigationItems not action! I want when click on NavigationItems, start other Activities.
Main XML :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/backgroundPrimary"
tools:context="com.tellfa.dastanak.Activities.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/main_appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|snap"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.tellfa.dastanak.Components.CodeSaz_TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:singleLine="true"
android:textColor="#color/textLight"
android:textSize="25sp" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/main_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#color/tabIndicatorColor" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/main_viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/menu_header"
app:itemIconTint="#color/colorPrimary"
app:itemTextColor="#color/colorPrimary"
app:menu="#menu/menu_main_page" />
</android.support.v4.widget.DrawerLayout>
Main code :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar toolbar;
private DrawerLayout mDrawerLayout;
private ViewPager viewPager;
private TabLayout tabLayout;
private DataBase dataBase;
private Cat1_frag_AsyncTask task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataBase = new DataBase(this);
try {
dataBase.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
TextView toolbar_text = (TextView) findViewById(R.id.toolbar_title);
toolbar_text.setText(R.string.app_name_fa);
final ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("");
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_driver);
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
viewPager = (ViewPager) findViewById(R.id.main_viewPager);
if (viewPager != null) {
setupViewPager(viewPager);
}
tabLayout = (TabLayout) findViewById(R.id.main_tabs);
if (tabLayout != null) {
tabLayout.setupWithViewPager(viewPager);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
case R.id.action_recyclerView:
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_recyclerView:
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
}
return onNavigationItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Main_frag_adapter mainFragAdapter = new Main_frag_adapter(getSupportFragmentManager());
mainFragAdapter.addFragment(new Cat1_fragment_recycler(), "آموزنده");
mainFragAdapter.addFragment(new Cat2_fragment_recycler(), "عاشقانه");
mainFragAdapter.addFragment(new Cat3_fragment_recycler(), "بزرگان");
mainFragAdapter.addFragment(new Cat4_fragment_recycler(), "متفرقه");
viewPager.setAdapter(mainFragAdapter);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void forceRTLIfSupported() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
}
How can i it? tnx <3
put this line
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
in
private void setupDrawerContent(NavigationView navigationView)
so updated method is like:
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
mDrawerLayout.closeDrawers();
return true;
}
});
}

Categories

Resources