I have an Activity that uses a NavigationView to display my app menu.
When menu opens and closes my App bar change from the drawer icon to the back arrow as expected.
I have a scenario, where i click on item 1 from my app menu, and it opens a fragment in my FrameLayout, and then i need to click a button that opens another fragment, replacing the previous one.
The app bar has the drawer icon in the 2 fragments, and i want to have a back arrow on the second fragment, so i can return to first fragment
Here is my MainActivity
public class MainActivity extends SuperActivity {
#BindView(R.id.nav_view) NavigationView navigationView;
#BindView(R.id.drawer_layout) DrawerLayout drawerLayout;
#BindView(R.id.container) FrameLayout frameLayout;
#BindView(R.id.toolbar) Toolbar toolbar;
ActionBarDrawerToggle drawerToggle;
SuperFragment nextFragment;
FragmentManager fragmentManager;
String activeName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fragmentManager = getSupportFragmentManager();
setupView();
if (savedInstanceState == null) showHome();
}
private void setupView() {
setSupportActionBar(toolbar);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(drawerToggle);
drawerLayout.setScrimColor(Color.TRANSPARENT);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
setupDrawerContent(navigationView);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(Gravity.LEFT);
activeName = item.getTitle().toString();
toolbar.setTitle(activeName);
selectDrawerItem(item);
return false;
}
});
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
private void showHome() {
selectDrawerItem(navigationView.getMenu().getItem(0));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
private void selectDrawerItem(MenuItem menuItem) {
drawerLayout.closeDrawer(Gravity.LEFT);
switch (menuItem.getItemId()) {...}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
drawerToggle.syncState();
super.onPostCreate(savedInstanceState);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
private Runnable Logout_Callback = new Runnable() {
public void run() {
Toast.makeText(getApplication(),"Log out",Toast.LENGTH_SHORT).show();
}
};
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
that extends from this
public class SuperActivity extends AppCompatActivity implements InterfaceHostActivity{
private SuperFragment selectedFragment;
// Navigation adapter
public NavigationListAdapter mNavigationAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void replaceFragment(SuperFragment fragment, boolean addToBackStack) {
replaceFragment(fragment, addToBackStack, R.id.container);
}
public void replaceFragment(SuperFragment fragment, boolean addToBackStack, int layout) {
try {
FragmentManager manager = getSupportFragmentManager();
if (fragment.isMainFragment) {
manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
String backStateName = ((Object) fragment).getClass().getName();
boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped) {
FragmentTransaction ft = manager.beginTransaction();
ft.replace(layout, fragment, backStateName);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
if (addToBackStack)
ft.addToBackStack(backStateName);
ft.commit();
}
getSupportFragmentManager().executePendingTransactions();
} catch (Exception e) {
LogManager.logException(e);
}
}
#Override
public void setSelectedFragment(SuperFragment fragment) {
this.selectedFragment = fragment;
}
#Override
public void popBackStack() {
getSupportFragmentManager().popBackStackImmediate();
}
#Override
public void popBackStackUntilTag(String tag) {
getSupportFragmentManager().popBackStackImmediate(tag, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
#Override
public void addFragment(SuperFragment fragment, boolean addToBackStack) {
try {
String backStateName = ((Object) fragment).getClass().getName();
String fragmentTag = backStateName;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
if (addToBackStack)
ft.addToBackStack(backStateName);
ft.commit();
} catch (Exception e) {
LogManager.logException(e);
}
}
#Override
public void addMultipleFragments(SuperFragment[] fragments) {
}
#Override
public void onBackPressed() {
boolean eventConsumed = false;
if (selectedFragment != null) {
eventConsumed = eventConsumed || selectedFragment.onBackPressed();
}
if (!eventConsumed) {
super.onBackPressed();
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
}
and my 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="pt.sibs.android.mpos.activities.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" />
<include layout="#layout/toolbar" />
</RelativeLayout>
<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:customTypeface="#string/font_lato_light"
android:background="#color/menuBG"
android:layout_marginTop="?attr/actionBarSize"
app:itemTextColor="#color/drawer_text_color_selector"
app:itemTextAppearance="#style/TextViewBody"
app:itemIconTint="#color/menu_icon_selector"
app:itemBackground="#drawable/menu_item_bg"
app:menu="#menu/drawer_view"/>
</android.support.v4.widget.DrawerLayout>
Related
The app I am building uses navigation drawer android.support.v4.widget.DrawerLayout and MainActivity extends android.support.v7.app.AppCompatActivity. I have a parent fragment that is replaced by child fragment. On parent fragment default hamburger icon is properly toggling the navigation drawer. While on child fragment, hamburger icon is replaced by back arrow icon using this snippet
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar = (Toolbar) (getActivity()).findViewById(R.id.toolbar);
((MainActivity)getActivity()).setSupportActionBar(toolbar);
On child fragment back button click event is handled on onOptionsItemSelected() and hamburger icon is shown again for parent fragment on onStop().
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActivity().onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onStop() {
super.onStop();
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
MainActivity.toggle.syncState();
}
On parent fragment hamburger icon is now showing properly but on clicking it the navigation drawer doesn't show up again.
Could anyone please help on what am I doing wrong?
Here are the relevant files:
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
try {
Fragment fragment = (Fragment) ParentFragment.class.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_content, fragment).commit();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
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();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
ParentFragment.java
public class ParentFragment extends Fragment implements View.OnClickListener {
public static ParentFragment newInstance() {
ParentFragment fragment = new ParentFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onClick(View v) {
int i = v.getId();
Fragment fragment = null;
if(i == R.id.child_fragment_button) {
fragment = new ChildFragment();
}
if(fragment != null) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_content, fragment)
.addToBackStack(null)
.commit();
}
}
}
ChildFragment.java
public class ChildFragment extends Fragment {
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Show back button
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar = (Toolbar) (getActivity()).findViewById(R.id.toolbar);
((MainActivity)getActivity()).setSupportActionBar(toolbar);
}
#Override
public void onStop() {
super.onStop();
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
MainActivity.toggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getActivity().onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I finally came up with the solution. Thanks to this answer.
Here are the changes I made:
ChildFragment.java
public class ChildFragment extends Fragment {
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Show back button
toggle = MainActivity.toggle;
toggle.setDrawerIndicatorEnabled(false);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getActivity().getSupportFragmentManager();
manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
toggle.setDrawerIndicatorEnabled(true);
}
});
toolbar = (Toolbar) (getActivity()).findViewById(R.id.toolbar);
toolbar.setNavigationIcon(((MainActivity)getActivity()).getDrawerToggleDelegate().getThemeUpIndicator());
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
}
I have a main activity with navigation drawer and a button to load fragment.
When the main ativity is launched I load the MainFragment.
In this moment all works well. The hamburger icon is showing and my Main fragment was loaded.
Next, I click a button and load a secondFragment. After I load the second fragment, I can use the backbutton and homebutton to come back to main activity without problems.
When I am with second fragment loaded and I make a rotation screen, the back button continues to work well, but the home button disappears and hamburger icon appears.
What am i doing wrong?
public class MainActivity extends AppCompatActivity {
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String mSubTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
if (savedInstanceState != null) {
return;
}
MainActivityFragment mainFragment = new MainActivityFragment();
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//transaction.replace(R.id.fragment_container, firstFragment);
transaction.replace(R.id.fragment_container, mainFragment, "princ");
transaction.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Only handle with DrawerToggle if the drawer indicator is enabled.
if (actionBarDrawerToggle.isDrawerIndicatorEnabled() &&
actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
}
public Fragment getCurrentFragment(){
FragmentManager frgmgr = getSupportFragmentManager();
return frgmgr.findFragmentById(R.id.fragment_container);
}
#Override
public void onBackPressed() {
if (drawerLayout != null) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
return;
}
}
if ((getCurrentFragment() instanceof MainFragment)) {
finish();
} else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else super.onBackPressed();
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
FragmentManager frgmgr = getSupportFragmentManager();
FragmentTransaction transaction = frgmgr.beginTransaction();
Fragment cur_frag;
// Handle navigation view item clicks here.
int id = menuItem.getItemId();
switch (id) {
case R.id.home:
cur_frag = frgmgr.findFragmentById(R.id.fragment_container);
if (!(cur_frag instanceof MainActivityFragment)) {
MainActivityFragment frag = new MainActivityFragment();
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
transaction.replace(R.id.fragment_container, frag);
transaction.commit();
break;
}
drawerLayout.closeDrawers();
break;
case R.id.logout_drw:
finish();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView) header.findViewById(R.id.tv_email);
tv_email.setText("Agendamento");
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mTitle = mDrawerTitle = getTitle();
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View v) {
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
if (toolbar != null) {
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
int i=getSupportFragmentManager().getBackStackEntryCount();
if ((i > 0) || (!(getCurrentFragment() instanceof MainActivityFragment))) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBarDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
}
}
}
Main Fragment:
public class MainFragment extends Fragment {
public MainFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_main, container, false);
Button butCons= (Button) view.findViewById(R.id.butcons);
butCons.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SecundaryFrag frag = new SecundaryFragFrag();
// Add the fragment to the 'fragment_container' FrameLayout
FragmentTransaction transaction=getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
transaction.replace(R.id.fragment_container, frag);
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
Secondary Fragment:
public class SecundaryFrag extends Fragment{
public SecundaryFrag() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_consulta_ag, container, false);
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
((MainActivity)getActivity()).onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
After Rotation:
Main activty with main fragment:
Before Rotation:
I believe it is related to the fact that the view is recreated after the orientation change. I would take a closer look to the onCreate() from the MainActivity in particular when the
if (savedInstanceState != null) {
return;
}
is triggered.
One option is to retain the fragments and restoring them onCreate. Also you could turn off the recreation by catching the orientation and handle it yourself in the application, you can see here both options explained developer.android.com/guide/topics/resources/
In my app I have the following navigationview.
So when the user click the menu item Καλώς ήρθες(meaning welcome in Greek),I want the this to be shown in the toolbar. This is my code for the navigationview.
public class Welcome extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private SessionManager session;
Toolbar toolbar;
private int mIconSize;
private String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
session = new SessionManager(getApplicationContext());
SharedPreferences userName = PreferenceManager.getDefaultSharedPreferences(this);
//UserId = userName.getString("id","");
username = userName.getString("user_name", "");
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
if (savedInstanceState == null) {
//Restore the fragment's instance and geo coordinates!
//homeFragment = (FragmentHome) getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
setSelected(R.id.welcome);
}else{
//profileFragment = (FragmentProfile) fm2.findFragmentByTag(PROFILE_FRAGMENT);
}
ActionBarDrawerToggle adt = new ActionBarDrawerToggle(this,drawerLayout,toolbar,
R.string.open_drawer,R.string.close_drawer){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.addDrawerListener(adt);
adt.syncState();
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setBackgroundColor(getResources().getColor(R.color.navigation_bg_color));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
drawerLayout.closeDrawers();
boolean result = setSelected(item.getItemId());
return result;
}
});
View v = navigationView.getHeaderView(0);
TextView t = (TextView)v.findViewById(R.id.username);
t.setText(username);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.log_out, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.log_out:
logoutUser();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logoutUser() {
session.setLogin(false);
// Launching the login activity
Intent intent = new Intent(Welcome.this, MainActivity.class);
startActivity(intent);
finish();
}
public boolean setSelected(int selected) {
switch (selected){
case R.id.welcome:
WelcomeFragment welcomeFragment = new WelcomeFragment();
FragmentManager fm1 = getSupportFragmentManager();
FragmentTransaction fragmentTra1 = fm1.beginTransaction();
fragmentTra1.replace(R.id.content,welcomeFragment);
//fragmentTra1.addToBackStack("added");
fragmentTra1.commit();
return true;
case R.id.general:
GeneralFragment generalFragment= new GeneralFragment();
FragmentManager fm2 = getSupportFragmentManager();
FragmentTransaction fragmentTra2 = fm2.beginTransaction();
fragmentTra2.replace(R.id.content,generalFragment);
//fragmentTra1.addToBackStack("added");
fragmentTra2.commit();
return true;
case R.id.announcements:
AnnouncementsFragment announcementsFragment= new AnnouncementsFragment();
FragmentManager fm3 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubOne = fm3.beginTransaction();
fragmentTraSubOne.replace(R.id.content,announcementsFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubOne.commit();
return true;
case R.id.sub_one:
NewsFragment newsFragment= new NewsFragment();
FragmentManager fm4 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubTwo = fm4.beginTransaction();
fragmentTraSubTwo.replace(R.id.content,newsFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubTwo.commit();
return true;
case R.id.sub_two:
FanClubFragment fanClubFragment= new FanClubFragment();
FragmentManager fm5 = getSupportFragmentManager();
FragmentTransaction fragmentTraSubThree = fm5.beginTransaction();
fragmentTraSubThree.replace(R.id.content,fanClubFragment);
//fragmentTra1.addToBackStack("added");
fragmentTraSubThree.commit();
return true;
}
return false;
}
public static Intent newIntent(Context context) {
return new Intent(context,MainActivity.class);
}
#Override
public void onBackPressed() {
if(isNavDrawerOpen()){
closeDrawerLayout();
}else {
super.onBackPressed();
}
}
public boolean isNavDrawerOpen() {
return drawerLayout!=null && drawerLayout.isDrawerOpen(GravityCompat.START);
}
private void closeDrawerLayout(){
if(drawerLayout != null){
drawerLayout.closeDrawer(GravityCompat.START);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
return (keyCode == KeyEvent.KEYCODE_BACK ? true :
super.onKeyDown(keyCode, event));
}
}
Any ideas?
Thanks,
Theo.
Try using setTitle():
public boolean setSelected(int selected) {
switch (selected){
case R.id.welcome:
toolbar.setTitle("Welcome");
......
}
.....
}
Try using:
getSupportActionBar().setTitle("title");
in the switch-case
I think you could use something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem item = menu.add(Menu.NONE, ID, POSITION, TEXT);
item.setIcon(R.drawable.drawable_resource_name);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
Also this link might help: Here
Hope it helps ;)
btw your app looks great!
I have one activity, inside I have toolbar and navigationView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_page_activity);
getFragment(new MainFragment());
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mNavigationView = (NavigationView) findViewById(R.id.main_drawer);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_widget);
drawerToggle
= new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
Log.i("StartPageActivity", "onPostCreate");
drawerToggle.syncState();
}
When starting activity at first called Main Fragment.
When I select item in NavigationView opens new Fragment.
when appear second fragment, inside I use
ActionBar a = ((AppCompatActivity) getActivity()).getSupportActionBar();
a.setDisplayHomeAsUpEnabled(true);
Up arrow appeared, but when I click on this Up arrow opens NavigationVIEW!!!
in fragment inside onOptionsItemSelected I HAVE
case android.R.id.home:{
Log.i("One", "Dude");
}
The program does not comply with this code. It does not come to it. I think the problem inside onCreate (activity). Maybe it conflict between ActionBarDrawerToggle, NavigationView and Toolbar.
ADD second fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.reminder_list_fragment, container, false);
getActivity().setTitle("Fragment1");
mRecyclerView = (RecyclerView)v. findViewById(R.id.my_recycler_view);
//{RecyclerAdapter}
ActionBar a = ((AppCompatActivity) getActivity()).getSupportActionBar();
a.setDisplayHomeAsUpEnabled(true);
a.setHomeButtonEnabled(true);
return v;
}
#Override
public void onResume() {
super.onResume();
mRecyclerView.getAdapter().notifyDataSetChanged();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.reminder_toolbar, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Log.d("Testing", "ID == " + id);
switch (id) {
case R.id.add_information : {
Forget f = new Forget();
ForgetLab.get(getActivity()).addForget(f);
FragmentManager fm = getFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
Bundle bundle = new Bundle();
bundle.putSerializable(ReminderFragment.EXTRA_FORGET_ID, f.getId());
if (mFragment != null) {
mFragment = new ReminderPagerFragment();
mFragment.setArguments(bundle);
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
return true;
}
case android.R.id.home:{
Log.i("One", "Dude");
}
}
return super.onOptionsItemSelected(item);
}
You should overRide onOptionsItemSelected(MenuItem item) and setHasOptionsMenu(true) should be called inside onCreate(Bundle savedInstanceState)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
getActivity().onBackPressed();
}
return super.onOptionsItemSelected(item);
} I hope this works....
Use this complete example.
public abstract class BaseActivity extends AppCompatActivity{
protected Toolbar toolbar;
protected User mMe;
protected DrawerLayout mDrawerLayout;
protected ActionBarDrawerToggle drawerToggle;
#Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
mMe = SessionUtils.getUser();
if (mMe == null) {
return;
}
initToolbar();
initInstances();
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void initInstances() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
if (mDrawerLayout != null) {
final NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
ImageView profileImage = (ImageView) navigationView.findViewById(R.id.profileImage);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityUtils.launchProfileActivity(BaseActivity.this, SessionUtils.getUser());
}
});
TextView name = (TextView) navigationView.findViewById(R.id.name);
final String fullName = StringUtils.getFullName(mMe.firstName, mMe.lastName);
name.setText(fullName);
GlideUtils.load(profileImage, mMe.getImage(), GlideUtils.getCircularFallbackDrawable(this, fullName), new CircleTransformGlide(this));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int itemId = menuItem.getItemId();
switch (itemId) {
case R.id.messages:
ActivityUtils.launchMessagesFragment(BaseActivity.this);
LogUtils.LOGD(">>Menu", "Messages");
break;
// case R.id.notification:
// LogUtils.LOGD(">>Menu", "Notification");
// break;
case R.id.friends:
LogUtils.LOGD(">>Menu", "find friends");
ActivityUtils.launchFriendsActivity(BaseActivity.this);
break;
case R.id.termsOfService:
ActivityUtils.launchTermsOfServiceFragment(BaseActivity.this);
break;
case R.id.friendsRrequests:
LogUtils.LOGD(">>Menu", "friendsRrequests");
ActivityUtils.launchFriendsRequests(BaseActivity.this);
break;
case R.id.logout:
LogUtils.LOGD(">>Menu", "Logout");
DialogUtils.LogoutConfirmDialogFragment logoutConfirmDialogFragment = new DialogUtils.LogoutConfirmDialogFragment();
logoutConfirmDialogFragment.show(getSupportFragmentManager(), "Logout Confirmation Fragment");
// LoginManager.reset(BaseActivity.this);
break;
}
// menuItem.setChecked(true);
// if (R.id.friends == itemId) {
// mDrawerLayout.postDelayed(new Runnable() {
// #Override
// public void run() {
// mDrawerLayout.closeDrawers();
// }
// }, 1000);
// } else {
// mDrawerLayout.closeDrawers();
// }
return true;
}
});
drawerToggle = new DrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name, new DrawerToggleListener() {
#Override
public void OnDrawerClose() {
}
#Override
public void OnDrawerOpen() {
}
});
mDrawerLayout.setDrawerListener(drawerToggle);
final ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null) {
supportActionBar.setHomeButtonEnabled(true);
supportActionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if (drawerToggle != null)
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (drawerToggle != null)
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return (drawerToggle != null && drawerToggle.onOptionsItemSelected(item)) || super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
private static class DrawerToggle extends ActionBarDrawerToggle {
DrawerToggleListener mToggleListener;
public DrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes, DrawerToggleListener toggleListener) {
super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
mToggleListener = toggleListener;
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
mToggleListener.OnDrawerClose();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
mToggleListener.OnDrawerOpen();
}
}
private static abstract class DrawerToggleListener {
public abstract void OnDrawerClose();
public abstract void OnDrawerOpen();
}
}
You Main activity must extends BaseActivity
public class MainActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!LoginManager.isFirstFlowFinished(this)) {
LoginManager.launchCurrentFragment(this);
finish();
return;
}
Intent intent = getIntent();
handleIntent(intent);
setContentView(R.layout.activity_main_new);
LogUtils.LOGD(">>Intent", "onCreate");
}
#Override
public void onResume() {
super.onResume();
LocationTracker.promptIfNeededForEnableLocation(this);
CommonUtils.checkIfPlayServicesNeedToUpdate(this);
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
AppEventsLogger.deactivateApp(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search_icon:
ActivityUtils.launchSearchActivity(this);
break;
}
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
LogUtils.LOGD(">>Intent", "on handle Intent");
handleIntent(intent);
}
}
And here is activity_main_new.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:minHeight="?actionBarSize"
android:background="?colorPrimary"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" >
<TextView
android:textColor="#color/white"
android:textSize="18sp"
android:textStyle="bold"
android:text="Friends Locator"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v7.widget.Toolbar>
<fragment
android:orientation="vertical"
android:id="#+id/viewPager"
android:name="com.macrotechnologies.friendslocator.ui.NearBySuggestionsFragment"
android:tag="com.macrotechnologies.friendslocator.ui.NearBySuggestionsFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:itemIconTint="#color/nav_item_icon_tint_color"
app:itemTextColor="#color/nav_item_text_color"
app:menu="#menu/navigation_drawer_items" />
and Navigation Menu item is as:
<?xml version="1.0" encoding="utf-8"?>
<group android:checkableBehavior="none">
<item
android:id="#+id/friends"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/friends_caps" />
<item
android:id="#+id/messages"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/messages" />
<item
android:id="#+id/friendsRrequests"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/friendsRequests" />
<!-- <item
android:id="#+id/notification"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/notifications" />-->
<!--<item-->
<!--android:id="#+id/about"-->
<!--android:icon="#drawable/ic_navigation_chevron_right"-->
<!--android:title="#string/about" />-->
<item
android:id="#+id/termsOfService"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/terms_of_service" />
<item
android:id="#+id/logout"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/log_out" />
</group>
I have an app in which I have a navigation panel with menu buttons on which I want to apply navigation drawer, currently it takes up the entire screen,but I want to restrict it to 3/4th of the screen by applying navigation drawer on it, but i have never touched navigation drawer before so have no clue, any help or guidance will be great.Also went through some documentation and got confused :(
Here is my code:
and here is my layout class for navigation panel:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/com.justin.a"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_texture"
android:clickable="true" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/nav_margin"
android:layout_marginTop="#dimen/nav_margin"
android:layout_marginRight="#dimen/nav_margin"
android:layout_marginBottom="#dimen/nav_margin"
android:background="#242424"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/nav_padding"
android:paddingTop="#dimen/nav_padding"
android:paddingRight="#dimen/nav_padding"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#android:drawable/divider_horizontal_bright"
android:orientation="vertical"
android:showDividers="middle"
>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_dashboard"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:layout_marginBottom="1px"
android:onClick="onDashboardClicked"
android:text="#string/nav_option_dashboard"
android:textSize="#dimen/navigation_panel_text"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_news"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
foo:customFont="cabin.medium.ttf"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:onClick="onNewsClicked"
android:text="#string/nav_option_news"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_markets"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:onClick="onMarketClicked"
android:text="#string/nav_option_markets"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_lists"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
android:text="#string/nav_option_lists"
foo:customFont="cabin.medium.ttf"
android:onClick="onListsClicked"
android:padding="#dimen/nav_option_padding"
android:background="#drawable/nav_background_button"
/>
<!-- UncommentForAlerts- Remove android:visibility="gone" -->
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_alerts"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:onClick="onAlertsClicked"
android:text="#string/nav_option_alerts"
android:background="#drawable/nav_background_button"
android:visibility="gone"
/>
<com.justin.a.utils.FontTextView
android:id="#+id/nav_option_briefcase"
style="#style/a.TextView.NavigationItem"
android:layout_width="match_parent"
android:layout_height="#dimen/button_ht"
android:textSize="#dimen/navigation_panel_text"
android:layout_marginBottom="1px"
foo:customFont="cabin.medium.ttf"
android:padding="#dimen/nav_option_padding"
android:onClick="onBriefcaseClicked"
android:text="#string/nav_option_briefcase"
android:background="#drawable/nav_background_button"
/>
</LinearLayout>
</ScrollView>
<ImageButton
android:id="#+id/button_information"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_centerHorizontal="true"
/>
<ImageButton
android:id="#+id/button_settings"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_toLeftOf="#+id/button_information" />
<ImageButton
android:id="#+id/button_logout"
android:layout_width="#dimen/nav_button"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/nav_padding"
android:layout_toRightOf="#+id/button_information"
/>
</RelativeLayout>
</RelativeLayout>
Also here is my navigationpanelfragment.java:
--UPDATE----
public class NavigationPanelFragment extends Fragment implements OnClickListener {
public static final String TAG_NAVIGATION_PANEL_FRAGMENT = "NavigationPanelFragment";
public static final String ACTIVE_MENU_ITEM = "ActiveMenuItem";
private ActionBarDrawerToggle drawerToggle;
private Fragment lvDrawer;
public static void newInstance(final FragmentManager manager, final String activeFragmentTag) {
final NavigationPanelFragment fragment = new NavigationPanelFragment();
final Bundle arguments = new Bundle();
arguments.putString(NavigationPanelFragment.ACTIVE_MENU_ITEM, activeFragmentTag);
fragment.setArguments(arguments);
final FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD);
fragmentInfo.setAnimation(R.anim.slide_in_from_left, FragmentInfo.NO_ANIMATION);
fragmentInfo.setPopAnimation(0, R.anim.slide_out_to_left);
fragmentInfo.setFragmentTag(TAG_NAVIGATION_PANEL_FRAGMENT);
fragmentInfo.doNotAddToBackStack();
fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.title_applications));
FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
}
public static void removeInstance(final FragmentManager manager) {
Fragment fragment = manager.findFragmentByTag(TAG_NAVIGATION_PANEL_FRAGMENT);
if (fragment == null) {
return;
}
manager.beginTransaction().setCustomAnimations(0, R.anim.slide_out_to_left).remove(fragment).commitAllowingStateLoss();
}
private LogoutListener mLogoutListener = new LogoutListener() {
#Override
public void onLogoutOperationFired() {
final Activity activity = getActivity();
if(activity != null){
LoginActivity.newInstance(activity);
UserProfileManager.clearUserProfileManager();
FragmentStackManager.getInstance().clearBackStack(getFragmentManager());
activity.finish();
}
}
};
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View view = inflater.inflate(R.layout.fragment_navigation_panel, container, false);
return view;
}
#SuppressWarnings("deprecation")
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ImageButton logoutButton = (ImageButton) getView().findViewById(R.id.button_logout);
logoutButton.setOnClickListener(this);
logoutButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_signout_nav_panel));
final ImageButton infoButton = (ImageButton) getView().findViewById(R.id.button_information);
infoButton.setOnClickListener(this);
infoButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_info_nav_panel));
final ImageButton settingsButton = (ImageButton) getView().findViewById(R.id.button_settings);
settingsButton.setOnClickListener(this);
settingsButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_prefs_nav_panel));
highlightActiveMenuItem();
}
#Override
public void onDestroy() {
super.onDestroy();
mLogoutListener = null;
}
#Override
public void onResume() {
MenuUtils.disableSearchMenu(getActivity());
MenuUtils.disableAlertMenu(getActivity());
super.onResume();
}
#Override
public void onPause() {
MenuUtils.enableSearchMenu(getActivity());
MenuUtils.enableAlertMenu(getActivity());
super.onPause();
}
#Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.button_logout:
final DialogFragment dialog = new LogoutCancelSignoutDialogFragment(mLogoutListener);
dialog.show(getActivity().getSupportFragmentManager(), AbsBaseaActivity.TAG_LOGOUT_DIALOG);
\ break;
case R.id.button_information:
leaveMainActivity();
InformationActivity.newInstance(getActivity());
\ break;
case R.id.button_settings:
leaveMainActivity();
PreferencesActivity.newInstance(getActivity());
\ break;
}
}
public ActionBarDrawerToggle getDrawerToggle() {
return drawerToggle;
}
private void leaveMainActivity() {
removeInstance(getActivity().getSupportFragmentManager());
final MainActivity activity = (MainActivity) getActivity();
activity.setNavigationOpen(false);
}
private void highlightActiveMenuItem() {
TextView highlightedTextView = null;
final String activeFragmentTitle = "";//getArguments().getString(ACTIVE_MENU_ITEM);
final Resources resources = Application.getAppResources();
if (resources.getString(R.string.nav_option_news).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_news);
} else if (resources.getString(R.string.nav_option_markets).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_markets);
} else if (resources.getString(R.string.nav_option_lists).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_lists);
} else if (resources.getString(R.string.nav_option_alerts).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_alerts);
}
else if (resources.getString(R.string.nav_option_briefcase).equals(activeFragmentTitle)) {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_briefcase);
} else {
highlightedTextView = (TextView) getView().findViewById(R.id.nav_option_dashboard);
}
highlightedTextView.setTextColor(getResources().getColor(R.color.dark_orange));
}
}
Here is my acitvity_main.xml (it works, shows a blank panel on swipe)
<?xml version="1.0" encoding="utf-8"?>
<!-- <include layout="#layout/main_title"/> -->
<!-- <Button android:text="Main" android:layout_height="wrap_content"
android:id="#+id/btn_refreshbtn_refresh" android:layout_width="wrap_content">
</Button> -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2">
</FrameLayout>
<fragment
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#666"
android:dividerHeight="1dp"
android:background="#333"
android:paddingLeft="15sp"
android:paddingRight="15sp"
android:name="com.justin.jar.fragments.NavigationPanelFragment"/>
</android.support.v4.widget.DrawerLayout>
----UPDATED----
Also here is my mainactivity.java (it has the navigation panel reference which i need to add under navigation drawer):
public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
public static final int REQUEST_CODE_LIST = 100;
private boolean mIsNavigationOpen = false;
private DrawerLayout drawerLayout;
private NavigationPanelFragment dlDrawer;
private ActionBarDrawerToggle actionBarDrawerToggle;
private boolean mIsSearchBarActive;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
public boolean isNavigationOpen() {
return mIsNavigationOpen;
}
#SuppressWarnings("deprecation")
public void setNavigationOpen(final boolean isNavigationOpen) {
this.mIsNavigationOpen = isNavigationOpen;
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
if(isNavigationOpen) {
mainButton.setBackgroundResource(R.drawable.bg_helios_active);
} else {
mainButton.setBackgroundDrawable(null);
}
}
public static void newInstance(final Activity activity) {
final Intent intent = new Intent(activity, MainActivity.class);
activity.startActivity(intent);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// 2. App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// 2.1 create ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close);
// 2.2 Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
initiateMainActionBar();
final FragmentManager supportFragmentManager = getSupportFragmentManager();
supportFragmentManager.addOnBackStackChangedListener(this);
if (savedInstanceState == null) {
mActiveFragment = DashboardFragment.getInstanceWithTransition(supportFragmentManager);
} else {
//resetToDashboard(supportFragmentManager);
}
//setup drawer
/* Set up the drawer toggle */
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.arrow_up, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle("");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
}
#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 (dlDrawer.getDrawerToggle().onOptionsItemSelected((android.view.MenuItem) item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
private void setupOnClickListenerForMainButton() {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
toggleNavigationPanel();
}
});
}
#Override
public void manageActionBar() {
setTitle(null);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggleNavigationPanel();
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onResume() {
final IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastActions.USER_PROFILE);
filter.addAction(BroadcastActions.NEWS_IMAGE);
filter.addAction(BroadcastActions.NEWS_HEADLINES);
registerReceiver(mMainActivityReceiver, filter);
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(mMainActivityReceiver);
super.onPause();
BangoAgent.onIdle();
}
public void pushNewsArticlePagerFragment(final int position, final String selectedCategoryCode, final boolean isMyNews) {
NewsArticlePagerFragment.newInstance(getSupportFragmentManager(), position, selectedCategoryCode, isMyNews);
}
public void onDashboardClicked(final View view) {
toggleNavigationPanel();
if (isFragmentVisible(DashboardFragment.TAG_DASHBOARD_FRAGMENT)) {
return;
}
final FragmentManager manager = getSupportFragmentManager();
final FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = DashboardFragment.getInstance();
transaction.hide(mActiveFragment);
transaction.show(mActiveFragment);
transaction.commitAllowingStateLoss();
updateActionBarTitle();
}
public void onNewsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onMarketClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(MarketsFragment.TAG_MARKETS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = MarketsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onListsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onBriefcaseClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(BriefcaseFragment.TAG_BRIEFCASE_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = BriefcaseFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onAlertsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(AlertsContainerFragment.TAG_ALERTS_CONTAINER_FRAGMENT)){
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = AlertsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
private void toggleNavigationPanel() {
final FragmentStackManager manager = FragmentStackManager.getInstance();
if (mIsNavigationOpen) {
NavigationPanelFragment.removeInstance(getSupportFragmentManager());
updateActionBarTitle();
BangoHelper.eventMainNav();
} else {
final TextView title = (TextView) findViewById(R.id.main_title);
title.setText(getString(R.string.title_applications));
NavigationPanelFragment.newInstance(getSupportFragmentManager(), manager.getTopTitle());
}
setNavigationOpen(!mIsNavigationOpen);
}
public void updateActionBarTitle() {
final String title = FragmentStackManager.getInstance().getTopTitle();
final TextView titleView = (TextView) findViewById(R.id.main_title);
titleView.setText(title);
}
private boolean isFragmentVisible(final String tag) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
return fragment != null && tag.equals(fragment.getTag());
}
public interface BackPressListener<T extends Fragment> {
public boolean backPressed(MainActivity fragmentActivity);
}
private BackPressListener<Fragment> backPressListener = null;
public void setBackPressListener (final BackPressListener<Fragment> backPressListener) {
this.backPressListener = backPressListener;
}
#Override
public void onBackPressed() {
if (backPressListener != null) {
boolean b = false;
// Making sure we trigger the backPressed event if the listener is the top fragment
String bplTag = ((Fragment)backPressListener).getTag();
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
String topFragemtnTag = "";
if (topFragment != null) {
topFragemtnTag = topFragment.getTag();
}
if (mIsSearchBarActive) {
MenuUtils.hideSearchView(this);
mIsSearchBarActive = false;
} else if (mIsNavigationOpen) {
toggleNavigationPanel();
} else if (!FragmentStackManager.getInstance().popTopFragment()) {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
} else {
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
if (topFragment == null) {
mActiveFragment = DashboardFragment.getInstance();
((DashboardFragment)mActiveFragment).refreshDashboard();
} else if (topFragment instanceof AbsArticlePagerFragment) {
((AbsArticlePagerFragment) topFragment).forceUpdateTextSize();
} else if (topFragment instanceof AbsBaseArticleFragment) {
((AbsBaseArticleFragment) topFragment).forceUpdateTextSize();
}
}
updateActionBarTitle();
}
public void setActiveFragment(final Fragment fragment) {
mActiveFragment = fragment;
}
public void setIsSearchBarActive(final boolean isSearchBarActive){
mIsSearchBarActive = isSearchBarActive;
}
#Override
public void onBackStackChanged() {
for (int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++) {
final BackStackEntry bse = getSupportFragmentManager().getBackStackEntryAt(i);
Log.d("BackStack", "Changed: " + bse.getName());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_LIST) {
if (resultCode == RESULT_OK) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment because dashboard was never added to backstack
DashboardFragment.getInstance().onUpdate();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).onUpdate();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).onUpdate(data);
}
}
}
}
#Override
public void refreshScreen() {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment
DashboardFragment.getInstance().refreshScreen();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).refreshScreen();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).refreshScreen();
} else if (fragment instanceof MarketsFragment) {
((MarketsFragment) fragment).refreshScreen();
}else if (fragment instanceof AlertsContainerFragment) {
((AlertsContainerFragment) fragment).refreshScreen();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
dlDrawer.getDrawerToggle().onConfigurationChanged(newConfig);
}
}
This is a good article to follow for adding a navigation drawer: http://developer.android.com/training/implementing-navigation/nav-drawer.html
Your navigation drawer is showing a blank panel, because the drawer view in your activity_main.xml is a ListView (which you haven't set any data to).
You want to make this view your fragment.
Your activity_main.xml file should look like. Make sure to replace the class on the fragment tag to the correct class of your navigation fragment.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!-- This fragment container is your the place to put your activities content -->
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2" />
<!--
This is your navigation drawer. You can adjust the width here, but it should
be between 240dp and 320dp
-->
<fragment
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
class="com.yourapp.NavigationPanelFragment" />
</android.support.v4.widget.DrawerLayout>
Your MainActivity should look something like this:
public class MainActivity extends AbsBaseaActivity implements OnBackStackChangedListener {
public static final int REQUEST_CODE_LIST = 100;
private Fragment mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
public boolean isNavigationOpen() {
return mDrawerLayout.isDrawerOpen(mDrawer);
}
#SuppressWarnings("deprecation")
public void setNavigationOpen(final boolean isNavigationOpen) {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
if(isNavigationOpen) {
mainButton.setBackgroundResource(R.drawable.bg_helios_active);
} else {
mainButton.setBackgroundDrawable(null);
}
}
public static void newInstance(final Activity activity) {
final Intent intent = new Intent(activity, MainActivity.class);
activity.startActivity(intent);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
initiateMainActionBar();
final FragmentManager supportFragmentManager = getSupportFragmentManager();
supportFragmentManager.addOnBackStackChangedListener(this);
if (savedInstanceState == null) {
mActiveFragment = DashboardFragment.getInstanceWithTransition(supportFragmentManager);
BangoHelper.onStartSession(this);
} else {
resetToDashboard(supportFragmentManager);
}
//setup drawer
//this is our drawer layout that contains the navigation drawer and your content
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//this is the navigation drawer fragment
mDrawer = (NavigationPanelFragment) findViewById(R.id.drawer);
}
private void resetToDashboard(final FragmentManager supportFragmentManager) {
FragmentStackManager.getInstance().clearBackStack(supportFragmentManager);
mActiveFragment = DashboardFragment.getInstanceWithNoTransition(supportFragmentManager);
}
private void initiateMainActionBar() {
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.actionbar_main);
setupOnClickListenerForSearchButton(this);
setupOnClickListenerForMainButton();
setupOnClickListenerForSearchCancelButton(this);
setupOnClickListenerForSearchClearButton(this);
}
private void setupOnClickListenerForSearchCancelButton(final MainActivity activity) {
final Button cancelButton = (Button) findViewById(R.id.button_search_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
final View actionBarView = findViewById(R.id.action_bar_container);
mIsSearchBarActive = MenuUtils.changeActionBar(activity, actionBarView);
}
});
}
private void setupOnClickListenerForMainButton() {
final ImageButton mainButton = (ImageButton) findViewById(R.id.button_main);
mainButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
toggleNavigationPanel();
}
});
}
#Override
public void manageActionBar() {
setTitle(null);
getSupportActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggleNavigationPanel();
break;
default:
break;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
protected void onResume() {
final IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastActions.USER_PROFILE);
filter.addAction(BroadcastActions.NEWS_IMAGE);
filter.addAction(BroadcastActions.NEWS_HEADLINES);
registerReceiver(mMainActivityReceiver, filter);
BangoAgent.onResume();
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(mMainActivityReceiver);
super.onPause();
saveTextSize();
}
private void saveTextSize() {
final ContentResolver resolver = EikonApplication.getAppContext().getContentResolver();
final ContentValues contentValues = new ContentValues();
contentValues.put(GenericColumns.TEXT_SIZE, SharedPreferencesManager.getInstance().getTextSize().ordinal());
SqlArguments argument = SqlArgumentsFactory.generateUserProfileUpdateSqlArguments();
String where = argument.getWhereClause();
String[] whereArgs = argument.getWhereArgs();
resolver.update(UserProfileContentProvider.USER_PROFILE_URI, contentValues, where, whereArgs);
}
public void pushNewsArticlePagerFragment(final int position, final String selectedCategoryCode, final boolean isMyNews) {
NewsArticlePagerFragment.newInstance(getSupportFragmentManager(), position, selectedCategoryCode, isMyNews);
}
public void onDashboardClicked(final View view) {
toggleNavigationPanel();
if (isFragmentVisible(DashboardFragment.TAG_DASHBOARD_FRAGMENT)) {
return;
}
final FragmentManager manager = getSupportFragmentManager();
final FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left);
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = DashboardFragment.getInstance();
transaction.hide(mActiveFragment);
transaction.show(mActiveFragment);
transaction.commitAllowingStateLoss();
updateActionBarTitle();
}
public void onNewsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(NewsFragment.TAG_NEWS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = NewsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onMarketClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(MarketsFragment.TAG_MARKETS_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = MarketsFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onListsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(ListsContainerFragment.TAG_LIST_CONTAINER_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = ListsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onBriefcaseClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(BriefcaseFragment.TAG_BRIEFCASE_FRAGMENT)) {
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = BriefcaseFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
public void onAlertsClicked(final View view) {
if(mIsNavigationOpen) {
toggleNavigationPanel();
}
if (isFragmentVisible(AlertsContainerFragment.TAG_ALERTS_CONTAINER_FRAGMENT)){
return;
}
FragmentStackManager.getInstance().clearBackStack(getSupportFragmentManager());
mActiveFragment = AlertsContainerFragment.newInstance(getSupportFragmentManager());
updateActionBarTitle();
}
private void toggleNavigationPanel() {
if (mDrawerLayout.isDrawerOpen(mDrawer))
mDrawerLayout.closeDrawer(mDrawer);
else mDrawerLayout.openDrawer(mDrawer);
final FragmentStackManager manager = FragmentStackManager.getInstance();
setNavigationOpen(setNavigationOpen());
}
public void updateActionBarTitle() {
final String title = FragmentStackManager.getInstance().getTopTitle();
final TextView titleView = (TextView) findViewById(R.id.main_title);
titleView.setText(title);
}
private boolean isFragmentVisible(final String tag) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
return fragment != null && tag.equals(fragment.getTag());
}
public interface BackPressListener<T extends Fragment> {
public boolean backPressed(MainActivity fragmentActivity);
}
private BackPressListener<Fragment> backPressListener = null;
public void setBackPressListener (final BackPressListener<Fragment> backPressListener) {
this.backPressListener = backPressListener;
}
#Override
public void onBackPressed() {
BangoHelper.eventBack();
if (backPressListener != null) {
boolean b = false;
// Making sure we trigger the backPressed event if the listener is the top fragment
String bplTag = ((Fragment)backPressListener).getTag();
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
String topFragemtnTag = "";
if (topFragment != null) {
topFragemtnTag = topFragment.getTag();
if (bplTag != null && topFragemtnTag != null && bplTag.equals(topFragemtnTag)) {
b = backPressListener.backPressed(this);
}
}
if (b) {
return;
}
}
if (mIsSearchBarActive) {
MenuUtils.hideSearchView(this);
mIsSearchBarActive = false;
} else if (mIsNavigationOpen) {
toggleNavigationPanel();
} else if (!FragmentStackManager.getInstance().popTopFragment()) {
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
} else {
Fragment topFragment = FragmentStackManager.getInstance().getTopFragment();
if (topFragment == null) {
mActiveFragment = DashboardFragment.getInstance();
((DashboardFragment)mActiveFragment).refreshDashboard();
} else if (topFragment instanceof AbsArticlePagerFragment) {
((AbsArticlePagerFragment) topFragment).forceUpdateTextSize();
} else if (topFragment instanceof AbsBaseArticleFragment) {
((AbsBaseArticleFragment) topFragment).forceUpdateTextSize();
}
}
updateActionBarTitle();
}
public void setActiveFragment(final Fragment fragment) {
mActiveFragment = fragment;
}
public void setIsSearchBarActive(final boolean isSearchBarActive){
mIsSearchBarActive = isSearchBarActive;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_LIST) {
if (resultCode == RESULT_OK) {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment because dashboard was never added to backstack
DashboardFragment.getInstance().onUpdate();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).onUpdate();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).onUpdate(data);
}else if (fragment instanceof AlertsContainerFragment) {
((AlertsContainerFragment) fragment).onUpdate();
}
}
}
}
#Override
public void refreshScreen() {
Fragment fragment = FragmentStackManager.getInstance().getTopFragment();
if (fragment == null) { // Implies DashboardFragment
DashboardFragment.getInstance().refreshScreen();
} else if (fragment instanceof ListsContainerFragment) {
((ListsContainerFragment) fragment).refreshScreen();
} else if (fragment instanceof ListDetailsFragment) {
((ListDetailsFragment) fragment).refreshScreen();
} else if (fragment instanceof MarketsFragment) {
((MarketsFragment) fragment).refreshScreen();
}
}
#Override
public void retryLoginDelayedData(){
LoginFragment f = new LoginFragment();
f.login("delayed");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
FragmentStackManager stackManager = FragmentStackManager.getInstance();
Fragment topFragment = stackManager.getTopFragment();
if(topFragment != null){
if(topFragment instanceof ChartFragment){
ChartFragment.replaceInstance(((ChartFragment)topFragment), getSupportFragmentManager(), R.id.fragment_container);
}
}
}
}
Notice that the state of the navigation drawer is managed by the drawer layout. The DrawerLayout and the drawer fragment is bound up in the onCreate method.
Refer to the article i mentioned if you run into trouble.
--- EDIT ----
Below is an activity I have used in an app. It shows how to add the drawer toggle (the link I posted also shows this).
You should be able to merge this with your current activity and have a working navigation drawer.
public class SampleActivity extends AbsBaseaActivity {
private Fragment mDrawer;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerMenuItems = getResources().getStringArray(R.array.home_menu_drawer_titles);
mDrawer = (fragment) findViewById(R.id.drawer);
/* Set up the drawer toggle */
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_closed) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle(R.string.activity_title);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.app_name);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
/**
* Backward-compatible version of {#link ActionBar#getThemedContext()} that
* simply returns the {#link android.app.Activity} if <code>getThemedContext</code> is unavailable.
*/
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private Context getActionBarThemedContextCompat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return getActionBar().getThemedContext();
} else {
return this;
}
}
#Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
mDrawer.setItemChecked(0, true);
}
#Override public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawer)) {
mDrawerLayout.closeDrawer(mDrawer);
} else {
mDrawerLayout.openDrawer(mDrawer);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you are having errors, then post what the errors are.
U can get source ode for navigation drawer from the link below
http://hmkcode.com/android-creating-a-navigation-drawer/
copy this to workspace, or open as a new android project from existing source code.
right click on project > properties >java buildpath> add external jar> choose latest V13 support library from android sdks installed and in order and export tick the jar v13
again right click on project > properties >android>choose abs library. [google for library]
U will get error free working project
All the answer above are awesome but I found it little bit difficult to add it in my existing code so I have created a new class which uses animation and LayoutInflater to add view and removes the navigation drawer to the activity you can use it in fragment also.
NavigationDrawer.java
import android.app.Activity;
import android.support.constraint.ConstraintLayout;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
public class NavigationDrawer {
//State is the visible state
private Boolean state = false, Transition = false;
private ConstraintLayout mainView;
private ConstraintLayout navigationLayout;
private Animation show, hide;
public NavigationDrawer(Activity activity, ConstraintLayout view) {
this.mainView = view;
LayoutInflater layoutInflater = (LayoutInflater)
activity.getSystemService(LAYOUT_INFLATER_SERVICE);
navigationLayout = (ConstraintLayout) layoutInflater.inflate(R.layout.nav_drawer,
mainView, false);
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//Show animation
show = new TranslateAnimation(-displayMetrics.widthPixels, 0, 0, 0);
show.setDuration(500);
show.getFillAfter();
show.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Transition = true;
}
#Override
public void onAnimationEnd(Animation animation) {
Transition = false;
state = true;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
//Hide animation
hide = new TranslateAnimation(0, -displayMetrics.widthPixels, 0, 0);
hide.setDuration(500);
hide.getFillAfter();
hide.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
Transition = true;
}
#Override
public void onAnimationEnd(Animation animation) {
Transition = false;
state = false;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
public void toggle() {
if (!Transition) {
if (!state) {
mainView.addView(navigationLayout);
navigationLayout.startAnimation(show);
} else {
navigationLayout.startAnimation(hide);
mainView.removeView(navigationLayout);
}
}
}
}
To use this class.
NavigationDrawer navigationDrawer = new
NavigationDrawer(this,user_activity_main_layout);
//To toggle it
navigationDrawer.toggle();
Here user_activity_main_layout is the Id of root ConstrainLayout you can choose whatever you want.
This works perfect.