0

I want to implement the back button to my app. I'm using fragments that each show a different webview. Right now if I press the back button, it closes the app no matter where I am. I would like for it to go back, just like a browser. I have my MainActivity.java, fragment1.java, etc up to fragment5.java

Here is my MainActivity.java:

package com.----;

import java.util.Locale;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;

public class MainActivity extends FragmentActivity {

    SectionsPagerAdapter mSectionsPagerAdapter;
    ViewPager            mViewPager;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);


    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }


        @Override
        public Fragment getItem(int position) {

            Fragment fragment;
            switch (position) {
                case 0:
                    fragment = new fragment1();
                    break;
                case 1:
                    fragment = new fragment2();
                    break;
                case 2:
                    fragment = new fragment3();
                    break;
                case 3:
                    fragment = new fragment4();
                    break;
                case 4:
                    fragment = new fragment5();
                    break;
                default:
                    fragment  = null;
                    break;
            }
            return fragment;

        }

        @Override
        public int getCount() {
            return 5;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.tab1).toUpperCase(l);
                case 1:
                    return getString(R.string.tab2).toUpperCase(l);
                case 2:
                    return getString(R.string.tab3).toUpperCase(l);
                case 3:
                    return getString(R.string.tab4).toUpperCase(l);
                case 4:
                    return getString(R.string.tab5).toUpperCase(l);
            }
            return null;
        }
    }
}

And here is my fragment1.java:

package com.----;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;

public class fragment1 extends Fragment {


    WebView myWebView;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        View root = inflater.inflate(R.layout.fragment1, container, false);

        myWebView = (WebView) root.findViewById(R.id.webview1);
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.loadUrl("url");
        return root;

    }
}

If I try to use this solutions and I get a force close when I'm testing it and press the back button.

Here is a logcat of it.

Community
  • 1
  • 1
user2763406
  • 11
  • 1
  • 3

4 Answers4

1

In your activity override on backpressed:

@Override
    public void onBackPressed() {
        switch (mViewPager.getCurrentItem()) {
        case 0:
            if (!webViewGoBack(0)) {
                    //do something if webview cannot go back
            }
            break;
        case 1:

            break;
        default:

        }
    }

public boolean webViewGoBack(int num) {
        SectionsPagerAdapter adapter = ((SectionsPagerAdapter)mViewPager.getAdapter());
        Fragment f = (Fragment )adapter.getFragment(num);
        if (f!= null) {
            return f.webViewGoBack();
        }
        return false;
    }

f.webViewGoBack() the method in you fragment:

public boolean WebViewGoBack() {
if(webView.canGoBack()){
   webView.goBack();
   return true;
}
return false; //webview cannot go back, so use the method of the BackButton
}
inc
  • 205
  • 4
  • 15
0

Just override onBackPressed() methid of your Activity

Maxim Efimov
  • 2,747
  • 1
  • 19
  • 25
  • I tried this and nothing happens. When I test it on my phone, it vibrates and gets the input but nothing happens. IF I use it in conjunction with the other solutions, I still get a force close. – user2763406 Sep 17 '13 at 06:16
  • @user2763406 there is no `myWebView` initialization in the Activity. You should use the fragments one. – Maxim Efimov Sep 17 '13 at 06:30
  • How can I use the fragment one? – user2763406 Sep 17 '13 at 06:41
  • @user2763406 I think one of the best approaches is to crate in each fragment(or in its super-class) a method `tryGoBack()` and call it in `onBackPressed()`(remember to keep current fragment). In each fragment implement the method with body of your `onBackPressed()` method from the pastebin. – Maxim Efimov Sep 17 '13 at 06:45
  • How can I call it in `onBackPressed`? (Sorry about this if it is frustrating to you. I'm learning to code so this is all new to me. – user2763406 Sep 17 '13 at 08:19
  • @user2763406 save a reference to a current fragment you obtain in `getItem` method of `SectionsPagerAdapter`, and just call its method(as I mentioned - you should add a method like `goBackInWebView` in each fragment you use) – Maxim Efimov Sep 17 '13 at 08:37
  • Can you give me an example? (Again I'm sorry. Really a beginner here.) Also, I added a method to each fragment so now, the fragment file looks like this: http://pastebin.com/qynZFjhf but I get this error: `The method onBackPressed() is undefined for the type Fragment` – user2763406 Sep 17 '13 at 08:50
  • @user2763406 here it is: the activity http://pastebin.com/6zQvtjTe and the super-class for all your fragment(inherit them from it not from Fragment) http://pastebin.com/WmdQ8Vqh – Maxim Efimov Sep 17 '13 at 09:29
  • Thank you for helping me like this. I tried this and got a few errors. Here:`mSectionsPagerAdapter.getLastFragment().tryGoBack();` I got `The method tryGoBack() is undefined for the type WebViewFragment` and here:`case 0: fragment = new fragment1();` (same for each fragment) I got `Type mismatch: cannot convert from fragment1 to WebViewFragment` – user2763406 Sep 17 '13 at 09:57
  • @user2763406 inherit `fragment1` etc. from `WebViewFragment`. There might be typos as I did not launch the code. Try to find it out! – Maxim Efimov Sep 17 '13 at 10:03
  • I swear this is my last stupid question but how do I inherit fragment1? – user2763406 Sep 17 '13 at 10:08
  • @user2763406 don't write `extends Fragment`, write `extends WebViewFragment` instead in fragment classes defenition. I think you better read some books about Java before actuall Android development as it essentially needed for successfull development. – Maxim Efimov Sep 17 '13 at 10:13
  • I inherited `fragment1` and so forth from `WebViewFragment`. Now I only have an error on line 26 on `MainActivity` saying `The method tryGoBack() is undefined for the type WebViewFragment` and an error on line 79 saying `Type mismatch: cannot convert from WebViewFragment to Fragment`. I already checked and there doesn't seem to be any spelling errors. I am reading books on Java and android development as I'm going along. Just that some things do not translate well and I need the help of someone far more knowledgeable such as yourself. – user2763406 Sep 17 '13 at 15:50
  • @user2763406 method `tryGoBack` in `WebViewFragment` should be public, check that. Second code seems to be caused by wrong `WebViewFragment` class. It looks like it is not inherited from `Fragment`. – Maxim Efimov Sep 18 '13 at 02:23
  • Checked and it is definitely public. Also, if I mouse over the word `Fragment` in `Public Fragment getItem(int position)` I get this interesting tidbit of information: `Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found.`. Is that part of my problem? Also, note that I am using v4 support libraries so maybe that is part of the problem as well. – user2763406 Sep 18 '13 at 07:38
  • @user2763406 I don't see any problem with the message and support library, it's ordinar behaviour. Actually, I can't say you more what to do, you have to run your own investigation. – Maxim Efimov Sep 19 '13 at 02:19
0
FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager
                        .beginTransaction();
                First first_act = new First();

                fragmentTransaction.replace(R.id.fragment_container,
                        first_act);
                fragmentTransaction.addToBackStack("first_act");
                fragmentTransaction.commit();

Add these code in mainactivity , and then use this onbackpressed in fragment

@Override
  public void onBackPressed() {

  }
Nikhil Virupakshi
  • 482
  • 2
  • 13
  • 26
  • I get three errors: 1.Type mismatch: cannot convert from android.support.v4.app.FragmentTransaction to android.app.FragmentTransaction 2.First cannot be resolved to a type 3. fragment_container cannot be resolved or is not a field – user2763406 Sep 17 '13 at 07:51
-1

You can begin by overriding the back button press in your MainActivity

@Override
public void onBackPressed() {
    //super.onBackPressed()
    //handle the press here to switch fragments
}
Frank Yin
  • 1,920
  • 1
  • 17
  • 12