The case is the following: I have two types of users, type1 and type2. Both have to login in order to go to the main activity which has a Navigation Drawer. The items in the navigation drawer depends on the type of the user. How can I change the items of the navigation drawer at runtime after I know the user type.
MainActivity.java
package com.example.motassem.navdrawer;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final String SELECTED_ITEM_ID = "selected_item_id";
private static final String FIRST_TIME = "first_time";
private Toolbar mToolbar;
private NavigationView mDrawer;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private int mSelectedID;
private boolean mUserSawDrawer = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//mMainLayout = (LinearLayout) findViewById(R.id.main_content);
mToolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mToolbar);
mDrawer = (NavigationView) findViewById(R.id.main_drawer);
mDrawer.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, mToolbar,
R.string.drawer_open,
R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
if (!didUserSeeDrawer()) {
showDrawer();
markDrawerSeen();
} else {
hideDrawer();
}
mSelectedID = savedInstanceState == null ? R.id.navigation_item_1 : savedInstanceState.getInt(SELECTED_ITEM_ID);
if (mSelectedID == R.id.navigation_item_1) {
// This is the first time i.e. NO FRAGMENTS WERE ADDED BEFORE..?
}
navigate(mSelectedID);
}
private boolean didUserSeeDrawer() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
return sharedPreferences.getBoolean(FIRST_TIME, false);
}
private void markDrawerSeen() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mUserSawDrawer = true;
sharedPreferences.edit().putBoolean(FIRST_TIME, mUserSawDrawer).apply();
}
private void hideDrawer() {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
private void showDrawer() {
mDrawerLayout.openDrawer(GravityCompat.START);
}
private void navigate(int mSelectedID) {
switch (mSelectedID) {
// Edit here to navigate..
case R.id.navigation_item_1: // History was pressed.
mDrawerLayout.closeDrawer(GravityCompat.START);
getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new FragmentTotal()).commit();
break;
case R.id.navigation_item_2: // Stores was pressed.
mDrawerLayout.closeDrawer(GravityCompat.START);
getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new FragmentTransactionComplete()).commit();
break;
case R.id.navigation_item_3: // Settings was pressed.
mDrawerLayout.closeDrawer(GravityCompat.START);
getSupportFragmentManager().beginTransaction().replace(R.id.main_content, new FragmentUpdateCard()).commit();
break;
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mSelectedID = menuItem.getItemId();
navigate(mSelectedID);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(SELECTED_ITEM_ID, mSelectedID);
}
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
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"
tools:context="com.example.motassem.navdrawer.MainActivity">
<LinearLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</android.support.v7.widget.Toolbar>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/main_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:itemIconTint="#color/colorAccent"
app:itemTextColor="#color/colorTextSecondary"
app:menu="#menu/menu_drawer">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
menu_item.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_item_1"
android:icon="#drawable/ic_history"
android:title="#string/navigation_item_1" />
<item
android:id="#+id/navigation_item_2"
android:icon="#drawable/ic_cart"
android:title="#string/navigation_item_2" />
<item
android:id="#+id/navigation_item_3"
android:icon="#drawable/ic_card"
android:title="#string/navigation_item_3" />
</menu>
I found easier way to change navigation view ( work with both submenu and menu). You can re-inflate NavigationViewat runtime with 2 lines of code. In this example i re-inflate with new_navigation_drawer_items.xml when user successfully logged-in
navigationView.getMenu().clear(); //clear old inflated items.
navigationView.inflateMenu(R.menu.logged_in_navigation_drawer_items); //inflate new items.
When user log out just re-inflate again with logged_out_navigation_drawer_items.xml
navigationView.getMenu().clear(); //clear old inflated items.
navigationView.inflateMenu(R.menu.logged_out_navigation_drawer_items); //inflate new items.
Related
I want to make my navigation open from right to left. But as soon as I change any of these steps my program face to error force closed after click on navigation after running the app.
My main_activity.xml
<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" />
My custom_toolbar.xml
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="right"
android:background="#color/colorPrimary">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="title"
android:padding="8dp"
android:textColor="#fff"
android:textSize="18sp"
/>
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/cnews"
android:tint="#fff"
android:layout_gravity="right"
/>
</android.support.v7.widget.Toolbar>
//content
<include layout="#layout/content_main" /> </LinearLayout>
My appbar_main.xml
<include layout="#layout/toolbar_main" />
My main_activity.java
import android.app.FragmentManager; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home_page) {
Home_page_fragment homeFragment = new Home_page_fragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.mainContent , homeFragment, homeFragment.getTag()).commit();
} else if (id == R.id.tour_page) {
Tour_page_fragment tourFragment = new Tour_page_fragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.mainContent , tourFragment, tourFragment.getTag()).commit();
} else if (id == R.id.lstour_page) {
LsTour_page_fragment LstourFragment = new LsTour_page_fragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.mainContent , LstourFragment, LstourFragment.getTag()).commit();
} else if (id == R.id.hotel_page) {
} else if (id == R.id.agency_page) {
} else if (id == R.id.news_page) {
}else if (id == R.id.logbook_page) {
}else if (id == R.id.message_page) {
}else if (id == R.id.favorite_page) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
} }
I changed "Start" to "end" in .xml main activity and java main activity get force closed!
I change "start" to "right" get force closed!!
I used RTL library but again get forced closed!!!
Thanks in advance.
The problem is that your customized Gravity is not defined and returns NULL.
First of all, you should update your menu.xml and build an item as an icon for right menu, like this:
<item
android:id="#+id/menu_right"
android:orderInCategory="100"
android:showAsAction="always"
android:icon="#android:drawable/ic_dialog_dialer"
android:title="#string/action_menuright"
/>
And in main_activity.java disable the default toggle drawer which opened from left and update this:
toggle.syncState();
toggle.setDrawerIndicatorEnabled(false);//this is added line
and similary udate this one:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
< here: add this line: >
DrawerLayout drawer;
and finally change this class to:
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.menu_right) {
if(drawer.isDrawerOpen(Gravity.RIGHT) ) {
drawer.closeDrawer(Gravity.RIGHT);
}
else{
drawer.openDrawer(Gravity.RIGHT);
}
return true;
}
return super.onOptionsItemSelected(item);
}
and everything is fine now.
I suggest you that use this code to Oncreate main_activity.java :
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
I've created menu using DrawerLayout
MainActivity.java
package com.example.vsoftwares.hamburgermenu;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ListView mDrawerList,mDrawerList2;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// My code starts here
mDrawerList = (ListView)findViewById(R.id.navList); // changed listview to textview
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
ActionBar actionBar = getSupportActionBar();
addDrawerItems();
setupDrawer();
if (actionBar != null)
{
//actionBar.setTitle("My App Title");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
//getSupportActionBar().setDisplayShowHomeEnabled(true);
}
// ends here
}
// MY DRAWER CODE STARTS HERE
private void addDrawerItems() {
String[] osArray = { "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "have to add content", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
// getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
// ENDS HERE
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<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">
<!-- The first child in the layout is for the main Activity UI-->
<RelativeLayout
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"
tools:context=".MainActivity"
android:background="#FF4081">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="PAGE 1"
android:textSize="24sp"
android:gravity="center"
android:layout_marginTop="100dp"/>
</RelativeLayout>
<!-- Side navigation drawer UI -->
<ListView
android:id="#+id/navList"
android:layout_width="200dp"
android:text="hello"
android:layout_height="match_parent"
android:textColor="#000"
android:background="#FFFFFF"
android:layout_gravity="left|start"
/>
</android.support.v4.widget.DrawerLayout>
This is what I currently have:
I have tried spinner inside layout in my code, but it's not producing what I want. Please give me some help. I need it to look more like the following:
I'm trying to add an addtextchangedlistener event inside a navigationView edittext.
I want to add it so whenever I type characters in the textbox, it will automatically capture the text and then filter my menu using the text supplied.
What happens is when I run the app, it throws a null pointer exception on the
addTextChangedListener. How can I fix this to allow it to detect the input and control it from there?
this is my xml and class files:
nav_header_home.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="#dimen/nav_header_height"
android:background="#e3e4e5"
android:theme="#style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="#dimen/search_bar_layout_height"
android:id="#+id/editTextSearchBar"
android:background="#drawable/rounded_edittext"
android:hint="Search"
android:textColorHint="#color/colorSearchBarHint"
android:textAlignment="center"
android:drawableLeft="#drawable/ic_menu_search"
android:textColor="#color/colorProfileName"
/>
</LinearLayout>
<LinearLayout
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>
my HomeActivity class:
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import com.app.test.R;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
int mProfileMenuCtr = 0;
String [] mValues = {"Inbox","News","My Profile"};
EditText mSearchBar;
String mTempText;
int [] mTempCtr;
int mTempCtr2;
MenuItem mItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mSearchBar = (EditText)findViewById(R.id.editTextSearchBar);
mSearchBar.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mSearchBar.setError(null);
}
#Override
public void afterTextChanged(Editable s) {
mTempText = mSearchBar.toString();
mTempCtr2 = 0;
for(int o = 0;o <mValues.length;o++){
boolean containerContainsContent = mValues[o].toLowerCase().contains(mTempText.toLowerCase());
if(containerContainsContent)
{
mTempCtr2++;
mTempCtr [mTempCtr2] = o;
}
}
invalidateOptionsMenu();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_home_drawer, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.activity_home_drawer, menu);
hideMenuItems(menu, false);
return super.onPrepareOptionsMenu(menu);
}
private void hideMenuItems(Menu menu, boolean visible)
{
for(int i = 0; i < menu.size(); i++){
menu.getItem(i).setVisible(visible);
}
for(int ii = 0; ii < mTempCtr.length;ii++){
menu.getItem(ii).setVisible(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_inbox) {
} else if (id == R.id.nav_news) {
} else if (id == R.id.nav_my_profile) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Its too late to answer but here is my answer
Find navigation header and then find EditText
View header = navigationView.getHeaderView(0);
mSearchBar = (EditText) header.findViewById(R.id. editTextSearchBar);
then Add TextWatcher on EditText
This question might have been asked many times, but none of the solutions are working for me.
I have an activity that implements navigation drawer but the drawer toggle button is not working.
I don't know what I am missing, but it is really bothering me.
package com.hajiri.jolly;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Toolbar mToolbar;
ActionBarDrawerToggle mDrawerToggle;
DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.appbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
setSupportActionBar(mToolbar);
NavigationView view = (NavigationView) findViewById(R.id.navigation_view);
view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
mToolbar,
R.string.app_name,
R.string.app_name
);
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
getMenuInflater().inflate(R.menu.main, menu);
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is my layout file:
<RelativeLayout 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:layout_height="wrap_content"
android:layout_width="wrap_content">
<include layout="#layout/appbar" android:id="#+id/appbar"/>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Main layout -->
<FrameLayout
android:id="#+id/fragment"
android:name="com.hajiri.jolly.StudentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_school"
android:layout_below="#+id/appbar" />
<!-- Nav drawer -->
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header_navigation_drawer"
app:menu="#menu/nav_menu"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
Edit
It seems that the buttons on action bar are not working altogether. Even the overflow button does not responds to clicks
I did followings:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} else {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
return super.onOptionsItemSelected(item);
}
and it works OK.
R.id.driver_layout - is my Layout in XML.
I created a Navigation drawer using the design support library. When I open the Navigation Drawer and click on the Volunteer menu item see image
I want the contents of the Volunteer screen with three tabs below and still able to access the navigation drawer displayed. I've tried implementing that code but the app crashes
I tried to use this example https://guides.codepath.com/android/Fragment-Navigation-Drawer. However the Activity that has the
I have attached the code for the Main Activity :
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.nav_geotag:
fragmentClass = (Fragment_GeoTag.class);
break;
case R.id.nav_footprint:
fragmentClass = Fragment_Footprint.class;
break;
case R.id.nav_education:
fragmentClass = Fragment_Education.class;
break;
case R.id.nav_rssfeeds:
fragmentClass = SimpleRSSReaderActivity.class;
break;
default:
fragmentClass = HomeActivity.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item, update the title, and close the drawer
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawerLayout.closeDrawers();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
;
//noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
return super.onOptionsItemSelected(item);
}
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
}
}
The Volunteer Fragment
import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
/**
* Created by s210121629 on 2015-07-01.
*/
public class Fragment_Volunteer extends AppCompatActivity{
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
#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 android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new PersonalinfoFragment(),"Personal Info");
adapter.addFragment(new MedicalinfoFragment(), "Medical Info");
adapter.addFragment(new ContactinfoFragment(), "Contact Info");
viewPager.setAdapter(adapter);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
The activity_main layout
<?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:fitsSystemWindows="true">
<!--<include layout="#layout/include_list_viewpager"/>-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
<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"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
profile activity layout
<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/sin"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true">
<include layout="#layout/profile_listview_pager"/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_view"/>
</android.support.v4.widget.DrawerLayout>
Logcat:
Process: com.example.s210121629.eama, PID: 3185
java.lang.NullPointerException
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:417)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:452)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:444)
at com.example.s210121629.eama.MainActivity.selectDrawerItem(MainActivity.java:108)
at com.example.s210121629.eama.MainActivity$1.onNavigationItemSelected(MainActivity.java:48)
at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:136)
at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at android.support.design.internal.NavigationMenuPresenter.onItemClick(NavigationMenuPresenter.java:179)
at android.widget.AdapterView.performItemClick(AdapterView.java:308)
at android.widget.AbsListView.performItemClick(AbsListView.java:1524)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3531)
at android.widget.AbsListView$3.run(AbsListView.java:4898)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
The Volunteer Fragment is not a Fragment as it extends AppCompatActivity. It should extend Fragment.
In the navigation drawer click listener you then should do something like this:
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new Fragment_Volunteer()).commit();
you should use only Activity: "MainActivity"
and when you show "Fragment_Volunteer" on item menu put inside switch case:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_container, new Fragment_Volunteer())
.commit();
use the code next:
Fragment_Volunteer extends Fragment
finally Fragment not use:
protected void onCreate(Bundle savedInstanceState) {}
the code correct is this:
public class Fragment_Volunteer extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_profile, container, false);
return view;
}
}
I hope to help, sorry for my bad english