android DrawerLayout navigation Fragment reload without click on DrawerLayout item - android

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.

Related

How to change the menu according to the fragment using navigation drawer

I'm using NavigationDrawer as the main activity, but when I go to another fragment I want to modify the menu, putting an arrow to back to the home and hide the search icon of the navbar, so I'm having two problems here, I can hide the search icon when I change the fragment, but when I'm back to the navigationMain it should be visible again, which is not happening, and if I am in another fragment the navigation bar must be removed and an arrow back must appear so I can get back to home, this is what I've tried so far:
public class NavigationMain extends ActionBarActivity{
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
static Toolbar toolbar;
TextView toolbartitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_main);
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
toolbartitle = (TextView) findViewById(R.id.titletool);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* 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) {
//getSupportActionBar().setTitle(mTitle);
toolbartitle.setText(mTitle);
getSupportActionBar().setDisplayShowTitleEnabled(false);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
//getSupportActionBar().setTitle(mDrawerTitle);
toolbartitle.setText(mDrawerTitle);
getSupportActionBar().setDisplayShowTitleEnabled(false);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
setSupportActionBar(toolbar);
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbartitle.setText("Nav");
toolbar.inflateMenu(R.menu.main);
mDrawerToggle.syncState();
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu 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
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, toolbartitle.getText());
// 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) {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = new InstituicoesFragment();
switch (position) {
case 0:
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
break;
}
// Load your conten here
Toast.makeText(NavigationMain.this, "Position" + position, Toast.LENGTH_LONG).show();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
//getSupportActionBar().setTitle(mTitle);
toolbartitle.setText(mTitle);
}
#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);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
In my Fragment I add the following:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
menu.removeItem(R.id.action_websearch);
super.onCreateOptionsMenu(menu, inflater);
}
i used this method :
i inflate the menu for the actionbar with all the items already in.
then in the Activity onCreateOptionsMenu() i check wich fragment is displayed and i set the visibility of the items accordingly.
then in the onSectionAttached method i call invalidateOptionsMenu(); that will reload the onCreateOptionsMenu so i can have different menu items on each fragment selected
for checking i use boolean flags and if the flag is true it means that the fragment is n view, like:
viewing the first fragment:
ft.replace(R.id.container, firstFragment);
firstfragmentIsOn=true;
secondFragmentIsOn=false;
viewing the second fragment:
ft.replace(R.id.container, secondFragment);
firstfragmentIsOn=false;
secondFragmentIsOn=true;
and in the onCreateOptionsMenu:
MenuItem item1=menu.findItem(R.id.item1);
MenuItem item2=menu.findItem)(R.id.item2);
if(firstfragmentIsOn)
{
item1.setVisible(true);
item2.setVisible(false);
}
if(secondFragmentIsOn)
{
item1.setVisible(false);
item2.setVisible(true);
}

Why Sliding Menu Can't Close in Android

Please I have a problem, in my code like its nothing wrong, why when I select content on Sliding Menu, Sliding menus are not automatically covered? What's wrong with my code? I do not use a fragment only uses a switch to display the menu
MainActivity.java
public class MainActivity extends FragmentActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mDrawerItems = getResources().getStringArray(R.array.list);
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 oepns
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// Add items to the ListView
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mDrawerItems));
// Set the OnItemClickListener so something happens when a
// user clicks on an item.
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
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);
// Set the default content area to item 0
// when the app opens for the first time
if(savedInstanceState == null) {
navigateTo(0);
}
}
/*
* If you do not have any menus, you still need this function
* in order to open or close the NavigationDrawer when the user
* clicking the ActionBar app icon.
*/
#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 super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
Intent i = new Intent(MainActivity.this, tentang.class);
startActivity(i);
}
if(mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/*
* When using the ActionBarDrawerToggle, you must call it during onPostCreate()
* and onConfigurationChanged()
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private class DrawerItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.v(TAG, "ponies");
navigateTo(position);
}
}
private void navigateTo(int position) {
Log.v(TAG, "List View Item: " + position);
switch(position) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
sejarah.newInstance(),
sejarah.sejarah).commit();
break;
case 1:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
pakaian.newInstance(),
pakaian.pakaian).commit();
break;
case 2:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
rumah.newInstance(),
rumah.rumah).commit();
break;
case 3:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
senjata.newInstance(),
senjata.senjata).commit();
break;
case 4:
Intent i = new Intent(MainActivity.this, lagu.class);
startActivity(i);
break;
case 5:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
musik.newInstance(),
musik.musik).commit();
break;
case 6:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame,
kesenian.newInstance(),
kesenian.kesenian).commit();
break;
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
}
you miss the the part drawer.closeDrawer(mDrawerList) or mDrawerLayout.closeDrawer(mDrawerList)

Menu only inflates onResume the Activity

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.

Android Navigation Drawer BaseActivity sample

Can someone suggest me a tutorial how to create a BaseActivity for the Android Navigation Drawer ?
Or can anyone post a sample BaseActivity for the Navigation Drawer including the layout ?
Download sample Code from Google n i have edited that code as basic navigation drawer with fragment no imageview
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
Fragment fragment = new PlanetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// mTitle = mDrawerTitle = getTitle();
// mPlanetTitles = getResources().getStringArray(R.array.planets_array);
// mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//mDrawerList = (ListView) findViewById(R.id.right_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, mPlanetTitles));
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
if (mDrawerLayout.isDrawerOpen(Gravity.END)==true)
{
mDrawerLayout.closeDrawers();
}else
{
mDrawerLayout.openDrawer(Gravity.END);
}
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 PlanetFragment();
Toast.makeText(getApplicationContext(), "You Select the Position"+position, Toast.LENGTH_SHORT).show();
Bundle args = new Bundle();
//args.putInt(PlanetFragment.ARG_PLANET_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(mPlanetTitles[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 PlanetFragment extends Fragment {
// public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.navigation_fragment, container, false);
// int i = getArguments().getInt(ARG_PLANET_NUMBER);
//String planet = getResources().getStringArray(R.array.planets_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 can achieve this with the help of fragments. Go through following which have sample code and video tutorial.
http://manishkpr.webheavens.com/android-navigation-drawer-example-using-fragments/
http://developer.android.com/training/implementing-navigation/nav-drawer.html

how to implement a merchandising display before starting my app

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.

Categories

Resources