Some features of Activity stops working onRestart() - android

I have created a navigation drawer in my application, Its working fine, but when i open another activity and go back to previous activity, the button of navigation drawer stops working, Although navigation drawer is still there. If i slide from left to right it opens the drawer, but when i click on Hamburger icon, it just doesn't do anything.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base_navigation);
ViewGroup content = (ViewGroup) findViewById(R.id.base_layout);
getLayoutInflater().inflate(getLayoutRes(), content, true);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout_main);
headerLayout= (FrameLayout) findViewById(R.id.header_layout);
btnOpenDrawer= (Button) findViewById(R.id.btn_openDrawer);
homeLayout= (LinearLayout) findViewById(R.id.home_layout);
btnOpenDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.openDrawer(Gravity.LEFT);
}
});
Kindly guide me that what i need to add in onRestart(). Do i need to write all this code in onRestart() as well?

Related

Convert Navigation Button into Back Button?

I, want to convert my navigation icon into back icon when I open my contact us fragment. for achieving this I have put this code.
#Override
public void onBackStackChanged() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container_dashboard);
if (f instanceof ContactUsFragment) {
notifications.setVisibility(View.GONE);
noti_count.setVisibility(View.GONE);
notifications.setEnabled(true);
mActionBarTitle.setText("Contact Us");
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimary));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.navigtion_back);
mToolbar.setNavigationIcon(R.drawable.navigtion_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
By this code when I am on Contact us fragment my navigation icon act as back icon. but the issue is my navigation icon not converted into back icon by this code. I searched on stack overflow and tried out these three codes to convert navigation icon into back icon but all three didn't work.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.navigtion_back);
mToolbar.setNavigationIcon(R.drawable.navigtion_back);

Up navigation in `AppCompatActivity` with `Fragments`

I am trying to set up proper navigation in my application, which replaces Fragments in a main content area, so I have only one single Activity. I have one main Fragment and several subFragments, for example a Fragment for preferences. Everything works fine when using the back button, but I want to implement the up navigation including icon in addition to this. I am using the ActionBar fetched with Activity.getSupportActionBar() together with a Toolbar from appcompat and an ActionBarDrawerToggle.
I followed this tutorial when setting up my Drawer in the first place.
Current behavior:
When I start the app, the list/drawer icon is shown in the left part of the ActionBar. When I click this, the Drawer opens and I can select items. Sub Fragments are replaced into my content and the back button pops the stack, taking me back to the previous Fragment.
Missing behavior:
The list/drawer icon in the top left is never replaced by the back arrow icon and I cannot figure out how to implement this properly. The Drawer is always pulled out when clicking the list/drawer icon, no matter which Fragment I am in.
What have I tried:
I tried following this answer. It kinda works, meaning that the back arrow icon is set in the sub Fragments, but clicking the back arrow still opens the Drawer instead of providing up navigation. Also, when using the back button to go "up", the list/drawer icon is replaced by nothing.
I also tried following this answer. Here, the desired ActionBar behavior/look is implemented in the onCreate() method of the various Fragments. Using this I could get the back arrow up, but still the Drawer is pulled when clicking the arrow.
Various other minor things and hacks.
My questions:
What is wrong in my code below?
Is it correct/normal to use the combination ActionBar, Toolbar and ActionBarDrawerToggle to implement the Drawer navigation together with up navigation?
MyActivity.onCreate():
#Override
protected void onCreate(Bundle savedInstanceState)
{
// Other stuff
// Setup drawer.
mDrawerFragment = (DrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.mm_navigation_drawer);
mDrawerFragment.initialize(this, (DrawerLayout)findViewById(R.id.mm_drawer_layout), toolbar);
}
DrawerFragment class
public class DrawerFragment extends Fragment
{
private MyActivity mMyActivity;
private MyActionBarDrawerToggle mMyBarDrawerToggle;
private DrawerLayout mDrawerLayout;
private FragmentDrawerListener mFragmentDrawerListener;
private View mContainerView;
public void initialize(MyActivity myActivity, final DrawerLayout drawerLayout, final Toolbar toolbar)
{
mMyActivity = myActivity;
mFragmentDrawerListener = mMyActivity;
mContainerView = myActivity.findViewById(R.id.mm_navigation_drawer);
mMyActionBarDrawerToggle = new MyActionBarDrawerToggle(myActivity, drawerLayout, toolbar, R.string.mm_drawer_open, R.string.mm_drawer_close);
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerListener(mMyActionBarDrawerToggle);
mDrawerLayout.post(new Runnable()
{
#Override
public void run()
{
mMyActionBarDrawerToggle.syncState();
}
});
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState)
{
// Not relevant, just create and return the View.
}
}
MyActivity.onDrawerItemSelected()
The implementation of the interface FragmentDrawerListener is done in the MyActivity class. It simply replaces the content area with other Fragments, using FragmentTransactions.
#Override
public void onDrawerItemSelected(View view, int postion)
{
switch (postion)
{
case DrawerAdapter.ITEM_FILTERED_RECIPES:
showFilteredRecipesFragment();
break;
case DrawerAdapter.ITEM_SELECTED_RECIPES:
showSelectedRecipesFragment();
break;
case DrawerAdapter.ITEM_SHOPPING_LIST:
showShoppingListFragment();
break;
case DrawerAdapter.ITEM_SETTINGS:
showSettingsFragment();
break;
case DrawerAdapter.ITEM_ABOUT:
showAboutFragment();
break;
}
}
MyActionBarDrawerToggle class
public class MyActionBarDrawerToggle extends ActionBarDrawerToggle
{
private MyActivity mMyActivity;
private Toolbar mToolbar;
public MyActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes)
{
super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
mMyActivity = (MyActivity) activity;
mToolbar = toolbar;
}
#Override
public void onDrawerOpened(View drawerView)
{
super.onDrawerOpened(drawerView);
mMyActivity.invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView)
{
super.onDrawerClosed(drawerView);
mMyActivity.invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
mToolbar.setAlpha(1 - slideOffset / 2);
}
}
The DrawerFragment is inflated in the main layout using a simple, static Fragment instance like this:
<fragment
android:id="#+id/my_navigation_drawer"
android:name="com.my.company.gui.drawer.DrawerFragment"
android:layout_width="#dimen/my_nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/my_drawer_navigation_fragment"
tools:layout="#layout/my_drawer_navigation_fragment">
</fragment>
If you're using material design for you app, then it is expected that you use the Toolbar to replace the Actionbar in your activity. You will still maintain your ActionBarDrawerToggle and functionality will remain the same.
As for your fragments, as long as they are 'housed' by the same activtiy (i.e the activity with the drawer), changing fragments will not cause the drawer toggle to change the back arrow. It will only change if you navigate to a new activity. Only then will the main activity be treated as home and with the other activities having a back arrow to navigate back

Back navigation with Fragments / Toolbar

I'm scratching my head with this one now.... I have an ActionBarActivity that loads an initial Fragment - the original menu is inflated within the activity. Now, I have a navigation bar that, when an item is selected, loads a different fragment and adds this to the backstack.
When I do this, there are a couple of things I want to set:
Set the home as up indicator
Invalidate the options menu from the main activity
Set has options to true for the Fragment
Ensure that the up indicator correctly navigates back to the original Fragment
Something rather strange is going on - the up indicator appears once only and does not behave as the back button and although I've invalidated and inflated a new menu, the new menu gets appended to the original Activity menu.
EDIT: Ok I've resolved the appending issue - forgot to add menu.clear() in the onCreateOptionsMenu method.
My navigation drawer layout has onClick methods to all menu items which would trigger the load of another Fragment:
public void navItemClick(View view) {
switch (view.getId()) {
case R.id.ripSMS:
mNavigationDrawer.toggleHome(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
FragmentTransaction mTrans = getSupportFragmentManager().beginTransaction();
mTrans.replace(R.id.voiceover_frame_layout,new MessageFragment(),"main_ui")
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).addToBackStack("msg").commit();
break;
case R.id.ripEmail:
break;
case R.id.ripSettings:
break;
}
mNavigationDrawer.closeDrawer();
}
toggleHome:
public void toggleHome(boolean show) {
mDrawerToggle.setDrawerIndicatorEnabled(show);
if (!show) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
} else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
}
Once the item is triggered the onCreate contains the invalidate and the hasOptions code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().invalidateOptionsMenu();
setHasOptionsMenu(true);
}
The onCreateOptionsMenu then inflates another menu layout (contains a single item called settings).
As mentioned, this only partially works once - the first time I use the item to load the Fragment, I get the back icon but it's also not working (this is set within onOptionsItemSelected to check for the home item press - it does nothing). When I press the back button it takes me back to the correct place. If I navigate back however, the back arrow now longer shows even though the code runs through onCreate!
Ok so I managed to solve this after some trial and error. Two changes made:
Implement addOnBackStackChangedListener
ActionBarDrawerToggle's setToolbarNavigationClickListener needed to be set
As I only have one activity (everything else is Fragment classes) I added the backstack listener to the Parent Activity's onCreate method:
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
}
});
This resolved the disappearing back arrow when going back to the fragment. Finally added the listener to my NavigationDrawer's setup class:
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
I suppose the only questions I have is everything pointed towards using the onOptionsItemSelected method with android.R.id.home but this never worked for me. It might be the way I've implemented things of course but if someone sees anything obvious as to why please do let me know!
These steps helps you to show back button in toolbar when a fragment is loaded. And to pop out when its clicked.
Set setNavigationOnClickListener to toolbar in you activity.
final 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();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(getSupportFragmentManager().getBackStackEntryCount() > 0){
getSupportFragmentManager().popBackStack();
}else {
drawer.openDrawer(GravityCompat.START);
}
}
});
Implement FragmentManager.OnBackStackChangedListener in you Activity. And register it with SupportFragmentManager in OnCreate()
getSupportFragmentManager().addOnBackStackChangedListener(this);
OnBackStackChangedListener Implementation method:
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() > 0){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
}
}
For me the above answer was not enough, but i've used #Hamz4h_ and added some more after digging into the ActionBarDrawerToggle class. I'm just calling this method of mine from the activity's onCreate:
private void initNavigationElements() {
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mBinding.drawerLayout, mBinding.appBarMain.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mBinding.drawerLayout.addDrawerListener(toggle);
// Tricking the toggle by giving it its own arrow as a custom indicator.
// It will use it when setDrawerIndicatorEnabled is called with false
toggle.setHomeAsUpIndicator(toggle.getDrawerArrowDrawable());
toggle.syncState();
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
DrawerArrowDrawable drawerArrowDrawable = toggle.getDrawerArrowDrawable();
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
// 1 - Display as arrow
drawerArrowDrawable.setProgress(1);
toggle.setDrawerIndicatorEnabled(false);
} else {
// 2 - Display as arrow menu
drawerArrowDrawable.setProgress(0);
toggle.setDrawerIndicatorEnabled(true);
}
}
});
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This is called only when setDrawerIndicatorEnabled is set as false, meaning we are not at the "root" fragment.
getSupportFragmentManager().popBackStackImmediate();
}
});
}
Hope this will help someone :)

Navigation Drawer with webview auto-closes after scrolling

I've put a webview on the Navigation Drawer; the webview shows formatted text about the current UI so that the users can familiarize themselves with features.
Unfortunately, after scrolling up or down on the webview (horizontal scrolling of the webview is disabled), the navigation drawer closes itself after I lift my finger off the webview !
How can I prevent the Navigation Drawer from closing itself when the user lets go ?
EDIT:
additional findings ... I've attached an OnTouchListener() to the drawer's layout that does nothing except return true. This prevents the auto-closing from happening when touching an empty space on the Navigation Drawer. To see how this is done, check out http://android-er.blogspot.com/2014/01/android-drawerlayout-and-drawerlistener.html and look at the "experimental" comment.
Unfortunately it doesn't stop the Navigation Drawer from closing when the user doesn't scroll up/down perfectly on the webview.
For example, scrolling up and down on the webview will close the drawer if there is a very small horizontal component to the drag.
So the (hassle-free) solution to prevent the over-zealous closing of the drawer: once the drawer is open, lock it open and have a button trigger the closeDrawer(). The code below shows how to manage the lock/unlock status. It doesn't include the button to call closeDrawer() because that's quite basic.
in XML, the id of the DrawerLayout is :
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
in your Activity, the java code is :
import android.support.v4.widget.DrawerLayout;
public class MyActivity extends Activity implements DrawerLayout.DrawerListener
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutwithdrawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(this);
}
#Override
public void onDrawerClosed(View arg0) {
// allow swiping to open the drawer
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
#Override
public void onDrawerOpened(View arg0) {
// disable swiping so that the drawer can't be closed by accident when scrolling through webview
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
}
#Override
public void onDrawerSlide(View arg0, float arg1) {}
#Override
public void onDrawerStateChanged(int arg0) {}
}

How to open navigation drawer on button click in main fragment?

I have made an app with one activity which uses a navigation drawer to open a number of different fragments. I have the actionbar drawertoggle, but it is not very visible.
If I place a button in the onCreateView in my main fragment(the fragment that appears when my app first starts up), how can I get it to open the navigation drawer controlled by my activity?
This seems to work. The answer is much simpler than I thought it would be.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragView = inflater.inflate(R.layout.mainmenu, container, false);
button1 = (Button) fragView.findViewById(R.id.button1);
mDrawerLayout = (DrawerLayout)getActivity().findViewById(R.id.drawer_layout);
mDrawerList = (ListView)getActivity().findViewById(R.id.left_drawer);
button1.setOnClickListener(this);
return fragView;
}
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(mDrawerList);
}
Thank you for your answers.
if you need open the slide:
mDrawerLayout.openDrawer(Gravity.LEFT); //Edit Gravity.START need API 14
if you need close the slide
mDrawerLayout.closeDrawer(Gravity.LEFT); //Edit Gravity.START need API 14
EXAMPLE
my mDrawerLayout is instanced here:
mDrawerLayout = (DrawerLayout)findViewById(R.id.my_drawer_layout);
my slide state:
mSlideState=false;
if you need to know the slide menu state (closed, opened). Use this code:
mDrawerLayout.setDrawerListener(new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_menu_slide,
0,
0){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
mSlideState=false;//is Closed
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
mSlideState=true;//is Opened
}});
finally. You can use your click event like this:
public void clickEventSlide(){
if(mSlideState){
mDrawerLayout.closeDrawer(Gravity.END);
}else{
mDrawerLayout.openDrawer(Gravity.END);
}}
In my case, my slide menu is at the right (Gravity.END), but if you need it on the left, try with Gravity.START
You Should Use isDrawerOpen()
The piece of code below automatically closes or opens the navigation drawer based on the drawer's current state (Opened or Closed)
Button hamMenu = findViewById(R.id.ham_menu);
hamMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DrawerLayout navDrawer = findViewById(R.id.drawer_layout);
// If the navigation drawer is not open then open it, if its already open then close it.
if(!navDrawer.isDrawerOpen(Gravity.START)) navDrawer.openDrawer(Gravity.START);
else navDrawer.closeDrawer(Gravity.END);
}
});
if you are using from default navigation activity in android you just have to
add this code in click listener of button --->
mDrawerLayout.openDrawer(Gravity.START);
for closing you do not have to do something.
Use these lines to open and close the drawer on a certain event:
Code snippet for opening drawer:
drawerLayout.openDrawer(Gravity.START);
Code snippet for closing drawer:
drawerLayout.closeDrawer(Gravity.LEFT);
→ openDrawer(gravity_of_navigation_view_to_be_shown)
in openDrawer("gravity"), in "gravity" section, you have to input the gravity of the Navigation View like given above:
Gravity.LEFT
Gravity.RIGHT
Gravity.START
Gravity.END
I think thats the best answer.
To apply the toolbar as the app bar, first make sure your activity extends from AppCompatActivity. Then call setSupportActionBar() and pass the Toolbar object from your layout:
toolbar=(Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp);
drawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle=new ActionBarDrawerToggle(this,drawerLayout,R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
}
The simplest way in my opinion
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(findViewById(R.id.navigationViewId))){
mDrawerLayout.closeDrawer(Gravity.LEFT);
}else
super.onBackPressed();
}

Categories

Resources