I want to implement drawer functionality in my android application just like flipkart can anyone help how to show subcategories in the same drawer on the click of respected category
Try to use Expandable listview in drawer like this
https://github.com/msahakyan/expandable-navigation-drawer
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter mExpandableListAdapter;
private List<String> mExpandableListTitle;
private Map<String, List<String>> mExpandableListData;
private TextView mSelectedItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mExpandableListView = (ExpandableListView) findViewById(R.id.navList);
mSelectedItemView = (TextView) findViewById(R.id.selected_item);
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.nav_header, null, false);
mExpandableListView.addHeaderView(listHeaderView);
mExpandableListData = ExpandableListDataSource.getData(this);
mExpandableListTitle = new ArrayList(mExpandableListData.keySet());
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData);
mExpandableListView.setAdapter(mExpandableListAdapter);
mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
getSupportActionBar().setTitle(mExpandableListTitle.get(groupPosition).toString());
mSelectedItemView.setText(mExpandableListTitle.get(groupPosition).toString());
}
});
mExpandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
getSupportActionBar().setTitle(R.string.film_genres);
mSelectedItemView.setText(R.string.selected_item);
}
});
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition))))
.get(childPosition).toString();
getSupportActionBar().setTitle(selectedItem);
mSelectedItemView.setText(mExpandableListTitle.get(groupPosition).toString() + " -> " + selectedItem);
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
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(R.string.film_genres);
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);
}
#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);
}
}
Related
I want to add slider down menu in Navigation Drawer like this.
After click left side icon, it shows like this.
What can be done for this ?
This is Navigation Drawer with ExpandableListview
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private String[] items;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter mExpandableListAdapter;
private List<String> mExpandableListTitle;
private NavigationManager mNavigationManager;
private Map<String, List<String>> mExpandableListData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mExpandableListView = (ExpandableListView) findViewById(R.id.navList);
mNavigationManager = FragmentNavigationManager.obtain(this);
initItems();
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.nav_header, null, false);
mExpandableListView.addHeaderView(listHeaderView);
mExpandableListData = ExpandableListDataSource.getData(this);
mExpandableListTitle = new ArrayList(mExpandableListData.keySet());
addDrawerItems();
setupDrawer();
if (savedInstanceState == null) {
selectFirstItemAsDefault();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void selectFirstItemAsDefault() {
if (mNavigationManager != null) {
String firstActionMovie = getResources().getStringArray(R.array.actionFilms)[0];
mNavigationManager.showFragmentAction(firstActionMovie);
getSupportActionBar().setTitle(firstActionMovie);
}
}
private void initItems() {
items = getResources().getStringArray(R.array.film_genre);
}
private void addDrawerItems() {
mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData);
mExpandableListView.setAdapter(mExpandableListAdapter);
mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
getSupportActionBar().setTitle(mExpandableListTitle.get(groupPosition).toString());
}
});
mExpandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
getSupportActionBar().setTitle(R.string.film_genres);
}
});
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition))))
.get(childPosition).toString();
getSupportActionBar().setTitle(selectedItem);
if (items[0].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentAction(selectedItem);
} else if (items[1].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentComedy(selectedItem);
} else if (items[2].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentDrama(selectedItem);
} else if (items[3].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentMusical(selectedItem);
} else if (items[4].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentThriller(selectedItem);
} else {
throw new IllegalArgumentException("Not supported fragment type");
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
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(R.string.film_genres);
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);
}
#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();
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
For more see this https://github.com/msahakyan/expandable-navigation-drawer
I am creating simple app having DrawerLayout navigation. In which one menu item is My Profile. In My profile Screen there is button which open Change Password screen in same Fragment. if i open DrawerLayout 's menu and close it without clicking, then My Profile Screen loads again.
Following is my code
public class HomeActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ArrayList<SideMenuEntity> listSideMenuItems;
private SideMenuAdapter adapterSideMenu;
Menu menu;
Fragment fragment;
AsyncTaskHelper loadFragmentTask;
int position, old_position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
listSideMenuItems = new ArrayList<>();
for(String str : Constant.SIDE_MENU_ITEMS)
{
listSideMenuItems.add(new SideMenuEntity(str));
}
// setting the nav drawer list adapter
adapterSideMenu = new SideMenuAdapter(getApplicationContext(),listSideMenuItems);
mDrawerList.setAdapter(adapterSideMenu);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayView(position);
}
});
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.mipmap.ic_launcher,R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu();
if (fragment != null) {
_setFragmentContainer(fragment, listSideMenuItems.get(position).title);
}
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null)
{
old_position = -1;
displayView(-1);
_setFragmentContainer(fragment, listSideMenuItems.get(position).title);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.menu = menu;
getMenuInflater().inflate(R.menu.menu_home_setting, menu);
_setActionBarHomeVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId())
{
case R.id.title_bar_home:
displayView(0);
return true;
case R.id.title_bar_setting:
_setFragmentContainer(new SettingFragment(), "Setting");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*
*/
protected void displayView(int p)
{
position = p >= 0 ? p : 0;
fragment = null;
switch (position)
{
case Constant.SIDE_MENU_ITEM_DAHSHBOARD:
fragment = new DashboardFragment();
break;
case Constant.SIDE_MENU_ITEM_MY_PROFILE:
fragment = new MyProfileFragment();
break;
}
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**-------------- private functions ---------------------*/
public void _setFragmentContainer(Fragment fragment, String title)
{
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
setTitle(title);
}
}
Try adding the super constructor:
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu();
if (fragment != null) {
_setFragmentContainer(fragment, listSideMenuItems.get(position).title);
}
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
i solve the problem my self own. actually whenever DrawerLayout closed, onDrawerClosed event fired, then i just null the fragment variable after _setFragmentContainer() function
if (fragment != null)
{
_setFragmentContainer(fragment, listSideMenuItems.get(position).title);
fragment = null;
}
Now DrawerLayout Menu closed, due to fragment null , it don't load fragment again.
I followed a tutorial to set a navigation drawer and it worked in my main activity. Now I tried to move it to almost every other activity creating a BaseActivity, but after making changes, navigation drawer icon is inactive, and does nothing when pressed.
MainActivity code:
public class MainActivity extends BaseActivity {
private WebView mWebView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//Hide the semy cirle at th bottom of the action bar when the user slides to the top
mWebView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
//mainWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.stopLoading(); // may not be needed
switch (Locale.getDefault().toString()) {
case "es_ES":
view.loadUrl("file:///android_asset/www/errorPage.forMainActivity.es_ES.HTML");
break;
default:
view.loadUrl("file:///android_asset/www/errorPage.forMainActivity.en_US.HTML");
break;
}
}
#Override
public void onPageFinished(WebView view, String url) {
//sendRegistrationIdToBackend();
//getCookies();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("CommentsPopUp")) {
Intent a = new Intent(MainActivity.this, CommentsPopUpActivity.class);
startActivity(a);
} else if (url.contains("postPopUp")) {
Intent b = new Intent(MainActivity.this, PostPopUpActivity.class);
startActivity(b);
} else if (url.contains("ProfilePicPopUp")) {
Intent c = new Intent(MainActivity.this, ProfilePicPopUpActivity.class);
startActivity(c);
} else if (url.contains("PostPicPopUp")) {
Intent c = new Intent(MainActivity.this, PostPicsPopUpActivity.class);
startActivity(c);
} else if (url.contains("reloadIndex")) {
mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/");
} else if (Uri.parse(url).getHost().length() == 0) {
return false;
} else { // Otherwise, give the default behavior (open in browser)
mWebView.loadUrl(url);
}
return true;
}
});
mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/");
// Stop local links and redirects from opening in browser instead of WebView
// mWebView.setWebViewClient(new MyAppWebViewClient());
}
#Override
public void onBackPressed(){
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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
public void getCookies() {
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie("http://192.168.0.6/");
//Log.i("UdazzT", cookies);
}
}
BaseActivity code:
public class BaseActivity extends AppCompatActivity {
ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
mNavItems.add(new NavItem(getResources().getString(R.string.myPosts), "", R.mipmap.ic_action_home));
mNavItems.add(new NavItem(getResources().getString(R.string.myFriends), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.findFriends), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.profileInfo), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.profilePic), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.notifications), "", R.mipmap.ic_action_settings));
mNavItems.add(new NavItem(getResources().getString(R.string.contact), "", R.mipmap.ic_action_settings));
mNavItems.add(new NavItem(getResources().getString(R.string.logOut), "", R.mipmap.ic_action_about));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigtion Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
// Drawer Item click listeners
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItemFromDrawer(position);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
}
#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_base, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle
// If it returns true, then it has handled
// the nav drawer indicator touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// 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 void onBackPressed(){
if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){ //replace this with actual function which returns if the drawer is open
mDrawerLayout.closeDrawer(Gravity.LEFT); // replace this with actual function which closes drawer
}
else{
super.onBackPressed();
}
}
/*
* Called when a particular item from the navigation drawer
* is selected.
* */
private void selectItemFromDrawer(int position) {
switch (position) {
case 0:
Intent a = new Intent(this, MyPostsActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(this, MyFriendsActivity.class);
startActivity(b);
break;
case 2:
Intent c = new Intent(this, FindFriendsActivity.class);
startActivity(c);
break;
case 3:
Intent d = new Intent(this, MyProfileInfoActivity.class);
startActivity(d);
break;
case 5:
Intent f = new Intent(this, MyNotificationsActivity.class);
startActivity(f);
break;
case 6:
Intent g = new Intent(this, ContactActivity.class);
startActivity(g);
break;
case 7:
//mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/signOut.php");
break;
}
mDrawerList.setItemChecked(position, true);
//setTitle(mNavItems.get(position).mTitle);
// Close the drawer
mDrawerLayout.closeDrawer(mDrawerPane);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
}
class NavItem {
String mTitle;
String mSubtitle;
int mIcon;
public NavItem(String title, String subtitle, int icon) {
mTitle = title;
mSubtitle = subtitle;
mIcon = icon;
}
}
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
#Override
public int getCount() {
return mNavItems.size();
}
#Override
public Object getItem(int position) {
return mNavItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
TextView subtitleView = (TextView) view.findViewById(R.id.subTitle);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText(mNavItems.get(position).mTitle);
subtitleView.setText(mNavItems.get(position).mSubtitle);
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
i have given this answer.
refer to this https://stackoverflow.com/a/30490289/3498931 and
in your case, implement syncState() method after the setting the listener to mDrawerLayout.
mDrawerLayout.setDrawerListener(drawerToggle);
after this statement, use the code i given in link. also you have duplication of code, remove the code from class which is not applicable. both way it is possible, but keep one only whichever works to avoid further conflict, unreadability or confustion.
I have an activity with NavigationDrawerFragment, shown here:
NavigationDrawerFragment.java
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
private EventActivity mainActivity = null;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainActivity = (EventActivity) getActivity();
mFragmentContainerView = inflater.inflate(R.layout.fragment_drawer_attendee, container, false);
... NOT IMPORTANT ...
mDrawerListView.setAdapter(new MenuEventAdapter(getActivity(), menuAL));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
mDrawerListView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
... NOT IMPORTANT ...
}
});
return mFragmentContainerView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
/*if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
*/
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
When I select an item from the drawer, it will add a new Fragment to the activity container.
Each fragment have it's own menu, as shown in the following example:
EventInformationFragment.java
public class EventInformationFragment extends Fragment
{
private View rootView = null;
private EventActivity mainActivity = null;
private GoogleMap mMap;
private boolean isStaff = false;
private LayoutInflater inflater = null;
private ViewGroup container = null;
private TextView forCopy = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
if(EventActivityHelper.getHelper().inSchedule)
{
return null;
}
mainActivity = (EventActivity) GlobalContents.getNowActivity();
mainActivity.getActionBar().setTitle(R.string.Event);
this.inflater = inflater;
this.container = container;
GlobalContents.dismissProgressBar();
if(!GlobalContents.getGlobalContents().getAuthenticatedUser().isStaff())
{
return elaborateAttendeeView();
}
isStaff = true;
return elaborateStaffView();
}
private View elaborateAttendeeView()
{
... NOT IMPORTANT ...
}
private View elaborateStaffView()
{
... NOT IMPORTANT ...
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
if(menu.hasVisibleItems())
menu.clear();
if(isStaff)
inflater.inflate(R.menu.event, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onPrepareOptionsMenu(Menu menu)
{
if(menu.hasVisibleItems())
menu.clear();
MenuInflater inflater = getActivity().getMenuInflater();
if(isStaff)
inflater.inflate(R.menu.event, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_edit:
mainActivity.getSupportFragmentManager()
.beginTransaction()
.remove(mainActivity.currentFragment)
.remove(getFragmentManager().findFragmentById(R.id.map))
.commit();
mainActivity.currentFragment = new EventEditInformationFragment();
mainActivity.getSupportFragmentManager().beginTransaction()
.add(R.id.container, mainActivity.currentFragment).commit();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
... NOT IMPORTANT ...
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
... NOT IMPORTANT ...
}
}
Here is the exact part of EventInformationFragment that I inflates the menu:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
if(menu.hasVisibleItems())
menu.clear();
if(isStaff)
inflater.inflate(R.menu.event, menu);
super.onCreateOptionsMenu(menu, inflater);
}
The problem is: when I open the Fragment through the NavigationDrawerFragment, the menu doesn't inflate!
In the EventInformationFragment, I intent to another activity, and, onResume this activity, the menu inflates!
What am I doing wrong?
Here is the activity that has the NavigationDrawerFragment and, at some point, EventInformationFragment
EventActivity.java
public class EventActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks
{
private static final String TAG = "EventActivity";
private NavigationDrawerFragment mNavigationDrawerFragment;
public Event currentEvent = null;
private PagerSlidingTabStrip tabs;
private ViewPager pager;
/* FOR TABBING */
private MyPagerAdapter adapter;
public Fragment currentFragment = null;
public Map<String, Fragment> fragments = null;
private Bundle instance;
public Vector<List<Lecture>> currentLectures = null;
private Calendar[] realScheduleDays;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_with_fragment_and_drawer);
currentEvent = GlobalContents.getGlobalContents().getCurrentEvent();
GlobalContents.setNowActivity(this);
if(GlobalContents.getGlobalContents().getAuthenticatedUser() == null)
{
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
finish();
}
else if(currentEvent == null)
{
Intent intent = new Intent(this, ProfileEventActivity.class);
startActivity(intent);
finish();
}
else
{
GlobalContents.getGlobalContents().setProgressBar();
/* DRAWER */
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
setTitle(getString(R.string.Event));
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, mDrawerLayout);
if(!EventActivityHelper.getHelper().inSchedule)
dismissTabsForSchedule();
else
loadTabsForSchedule();
/* CONTENT */
if (savedInstanceState == null)
{
EventActivityHelper.getHelper();
if(!EventActivityHelper.getHelper().inSchedule)
{
currentFragment = new EventInformationFragment();
fragments = new HashMap<String, Fragment>();
fragments.put(currentFragment.getClass().getName(), currentFragment);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, currentFragment).commit();
}
}
}
}
public void loadTabsForSchedule()
{
... NOT IMPORTANT ...
}
public void dismissTabsForSchedule()
{
... NOT IMPORTANT ...
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
/*fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();*/
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
//getMenuInflater().inflate(R.menu.event, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume()
{
super.onResume();
GlobalContents.setNowActivity(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
GlobalContents.setNowActivity(this);
switch(requestCode)
{
case Constants.FOR_REFRESH:
if(resultCode == Constants.FOR_REFRESH_OK)
{
currentLectures = null;
loadTabsForSchedule();
}
break;
}
}
... NOT IMPORTANT FROM NOW ON...
}
After a lot of search and tries, I've managed to make it work.
Before I commit the Fragment, I've placed an invalidateOptionsMenu().
It works now.
I have one problem, how to implement a merchandising display before starting my navigation drawer. this is my code. Thanks for help guys.
This is my code merchan, but is wrong, I want to call this screen before the application itself, which is basically a navigation drawer.
public class Merchan extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.merchan);
Thread logoTimer = new Thread() {
public void run() {
try {
sleep(3000);
Intent menuIntent = new Intent("com.codehevea.menu.Main");
startActivity(menuIntent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
finish();
}
}
};
logoTimer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
And this is my principal class. It should boot screen after merchandising.
public class Main extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mMenuTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mMenuTitles = getResources().getStringArray(R.array.menu_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mMenuTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available,
Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new MenuFragment();
Bundle args = new Bundle();
args.putInt(MenuFragment.ARG_MENU_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#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);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class MenuFragment extends Fragment {
public static final String ARG_MENU_NUMBER = "planet_number";
public MenuFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet,
container, false);
int i = getArguments().getInt(ARG_MENU_NUMBER);
String planet = getResources().getStringArray(R.array.menu_array)[i];
int imageId = getResources().getIdentifier(
planet.toLowerCase(Locale.getDefault()), "drawable",
getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image))
.setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
You're using the wrong Intent constructor. Change it to something like:
Intent menuIntent = new Intent(this, com.codehevea.menu.Main.class);
Note, if the current and target class are in the same package, you don't need the package name, so:
Intent menuIntent = new Intent(this, Main.class);
For more on this, visit Starting Another Activity.