且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎么回去1片段每次后退按钮是pressed?

更新时间:2023-11-21 17:06:46

评论/敲了这一点: FragmentUtils.onBack pressedKnockFragsOffStack(mainActivity,这一点);

I have a webview in a fragment container in which I have embedded a back functionality. It works fine for navigation within the webview with the device back button. However, when I click on the device back button to exit the fragment say I open fragment 1 containing news and then fragment 2 containing this webview and then i click device back button to go back to news fragment, it doesnt work, it ust goes back to the main page of the app. Here's the code class I am using. I am not sure how to go about it , do I have to edit to some backpressed() function ? if so how do I go about it or is there a way I can create if(goingback), return -1 for going back 1 step. Any ideas?

Thanks! Justin

@SuppressLint("ValidFragment")
public class MoneyWebViewFragment extends Fragment implements OnClickListener , MainActivity.BackPressListener<Fragment> {

    private static final String SEARCH_TERM = "search_term";
    private static String mSearchTerm;
    private WebView mWebview;
    private static MoneyWebViewFragment sUserProfileManager;


    public boolean mIsMoneyFragment;

    public  final static String SYMBOL = "symbol";

    public static int PIC_WIDTH = 30;
    private static final String SYMBOL_TYPE = "symbol_type";
    public  static final String CONTAINER_ID = "container_id";
    public static final String TAG_Money_FRAGMENT_WEBVIEW = "MoneyWebViewFragment";
    SharedPreferencesManager manager = SharedPreferencesManager.getInstance();
    private static  String URL;
    private final  String USERNAME = manager.getLoginUsername();
    private final  String PASSWORD = manager.getDecryptedLoginPassword();

    LinearLayout progressBar;
    private static MoneyWebViewFragment __newInstance(final MoneyWebViewFragment fragment, final FragmentManager manager,
            final String searchTerm, final String symbolType, int containerViewId, final int inAnimation, final int outAnimation, final int popInAnimation, final int popOutAnimation) {

        final Bundle bundle = new Bundle();
        bundle.putString(SEARCH_TERM, searchTerm);
        bundle.putString(MoneyWebViewFragment.SYMBOL_TYPE, symbolType);
        bundle.putInt(MoneyWebViewFragment.CONTAINER_ID, containerViewId);
        fragment.setArguments(bundle);

        FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD, containerViewId);
        fragmentInfo.setAnimation(inAnimation, outAnimation);
        fragmentInfo.setPopAnimation(popInAnimation, popOutAnimation);
        fragmentInfo.setFragmentTag(TAG_Money_FRAGMENT_WEBVIEW);
        fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.title_search));
        FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
        URL = getUrl();
        return fragment;
    }

     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            Bundle bundle = this.getArguments();
            URL = getUrl();

            if(bundle != null)
                mSearchTerm = getArguments().getString(SEARCH_TERM);

             }
     public void setSearchTerms(String sTerms){
         mSearchTerm = sTerms;
     }
    public static void removeInstance(final FragmentManager manager) {
        final MoneyWebViewFragment fragment = (MoneyWebViewFragment) manager.findFragmentByTag(TAG_Money_FRAGMENT_WEBVIEW);
        if (fragment == null) {
            return;
        }

        final FragmentStackManager stackManager = FragmentStackManager.getInstance();
        if (stackManager.getTopFragment() instanceof MoneyWebViewFragment) {
            stackManager.popTopFragment();
        }
    }
    private boolean goingBack = false;
    private boolean onBackPressClearStack = true;

    public void setOnBackPressClearStack(boolean b){
        onBackPressClearStack = b;
    }
    public boolean webViewSteppedBack() {
        if (mWebview != null && mWebview.canGoBack()) {
            WebBackForwardList mWebBackForwardList = mWebview.copyBackForwardList();
            String historyUrl = mWebBackForwardList.getItemAtIndex(mWebBackForwardList.getCurrentIndex()-1).getUrl();
            mWebview.goBack();

            return true;
        }
        return false;
    }



    private MoneyWebViewFragment() {
        mIsMoneyFragment = false;
    }
    public static synchronized void clearUserProfileManager() {
        sUserProfileManager = new MoneyWebViewFragment();
    }

    public static MoneyWebViewFragment getInstance() {
        if (sUserProfileManager == null) {
            sUserProfileManager = new MoneyWebViewFragment();
        }
        return sUserProfileManager;
    }
    public boolean isMoneyWebViewFragment() {
        return mIsMoneyFragment;
    }
    @Override
    public boolean backPressed(final MainActivity mainActivity) {
        if (webViewSteppedBack()) {
            return true;
        }

        if (onBackPressClearStack) {
            goingBack = true;
            FragmentUtils.onBackPressedKnockFragsOffStack(mainActivity, this);
        }
        return false;
    }
    private static String getUrl(){
        String url = "";

        final String environmentApi = SharedPreferencesManager.getInstance().getEnvironmentApi();
        if (environmentApi.equalsIgnoreCase(NetworkUtils.Apis.ALPHA)) {

                url = "https://abc.com?q="+mSearchTerm+"userAgent=android";



        } 

         return url;
    }


    private static MoneyWebViewFragment __newInstance(final MoneyWebViewFragment fragment, final FragmentManager manager,
            final String searchTerm, final String symbolType, int containerViewId) {

        return __newInstance(fragment, manager,searchTerm, symbolType, containerViewId, R.anim.slide_in_from_right, R.anim.slide_out_to_left, R.anim.slide_in_from_left, R.anim.slide_out_to_right);
    }
    private static void clearWebView(final FragmentManager manager) {
        final MoneyWebViewFragment fragment = (MoneyWebViewFragment) manager.findFragmentByTag(TAG_Money_FRAGMENT_WEBVIEW);
        if (fragment != null && fragment instanceof MoneyWebViewFragment) {
            ((MoneyWebViewFragment)fragment).clearWebView();
        }
    }

    public static MoneyWebViewFragment newInstance(final FragmentManager manager, final String searchTerm, String symbolType) {
        clearWebView(manager);
        return __newInstance(new MoneyWebViewFragment(), manager, searchTerm, symbolType, R.id.fragment_container);
    }

    public static MoneyWebViewFragment newInstance(final FragmentManager manager, final String searchTerm, String symbolType, int containerViewId) {
        clearWebView(manager);
        return __newInstance(new MoneyWebViewFragment(), manager, searchTerm, symbolType, containerViewId);
    }

    public static MoneyWebViewFragment newInstanceNoBackPressed(final FragmentManager manager, final String searchTerm,  final String symbolType, int containerViewId) {
        MoneyWebViewFragment fragment =  __newInstance(new MoneyWebViewFragment(), manager, searchTerm, symbolType, containerViewId);
        fragment.setOnBackPressClearStack(false);
        return fragment;
    }

    public static MoneyWebViewFragment newInstanceNoBackPressed(final MoneyWebViewFragment fragment, final FragmentManager manager, final String searchTerm, final String symbolType, int containerViewId) {
        fragment.setOnBackPressClearStack(false);
        return __newInstance(fragment, manager, searchTerm, symbolType, containerViewId);
    }

    public static MoneyWebViewFragment newInstanceForSearch(final FragmentManager manager, final String searchTerm, String symbolType) {
        MoneyWebViewFragment fragment = __newInstance(new MoneyWebViewFragment(), manager, searchTerm, symbolType, R.id.fragment_container, R.anim.no_animation, R.anim.slide_out_to_right, R.anim.slide_in_from_right, R.anim.slide_out_to_right);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        final MainActivity activity = (MainActivity) getActivity();
        activity.updateActionBarTitle();
        activity.setBackPressListener(this);

        }
    public void clearWebView() {
        if (mWebview != null) {
            mWebview.removeAllViews();
            mWebview.destroy();
            mWebview = null;
        }
    }
    @Override
    public void onClick(View v) {


    }

    @SuppressWarnings("deprecation")
    @SuppressLint({
            "SetJavaScriptEnabled", "NewApi"
    })
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (goingBack) {
            return null;
        }
        final MainActivity activity = (MainActivity) getActivity();

        activity.setBackPressListener(this);
        View view = inflater.inflate(R.layout.fragment_search_Money, container, false);


        mWebview =  (WebView)view.findViewById(R.id.webview);
        progressBar = (LinearLayout) view.findViewById(R.id.loading);   
        mWebview.setVisibility(View.VISIBLE);

        progressBar.setVisibility(View.VISIBLE);

            mWebview.setWebViewClient(new MyWebViewClient(this, mWebview));
            mWebview.getSettings().setUseWideViewPort(true);
            //mWebview.getSettings().setDefaultZoom(ZoomDensity.CLOSE);
            //mWebview.getSettings().setBuiltInZoomControls(false);
            //mWebview.getSettings().setSupportZoom(false);
            mWebview.setBackgroundColor(0);
            mWebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            mWebview.getSettings().setAllowFileAccess(true);
            mWebview.getSettings().setDomStorageEnabled(true);
            mWebview.getSettings().setJavaScriptEnabled(true);

            mWebview.setScrollbarFadingEnabled(false);
            mWebview.getSettings().getLoadsImagesAutomatically();

            mWebview.setWebChromeClient(new WebChromeClient() {
                   @Override
                   public void onReceivedTitle(WebView view, String title) {
                      super.onReceivedTitle(view, title);

                      String serverError = "412";
                      if (title.contains(serverError)) {
                          view.stopLoading();
                          SearchResultsFragment.newInstance(getFragmentManager(), mSearchTerm);
                      }
                   }
                });
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                mWebview.getSettings().setDisplayZoomControls(false);
            SharedPreferencesManager mgr = SharedPreferencesManager.getInstance();
            CookieStore cookieStore = mgr.getCookieStore();
            Cookie cookie = cookieStore.getCookies().get(0);
            String cookieString =  cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();
            CookieManager cookieMgr = CookieManager.getInstance();
            cookieMgr.setCookie(URL, cookieString);


            mWebview.loadUrl(URL);


        return view;
    }


    public class MyWebViewClient extends WebViewClient {

        //private String loginCookie;
        private int rIdParent_id = -1;
        public void setRIdParent_id (int id) {
            rIdParent_id= id; 
        }
        public MyWebViewClient(MoneyWebViewFragment MoneyWebViewFragment, WebView webview) {
            super();
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.setVisibility(View.VISIBLE);

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            view.setVisibility(View.VISIBLE);

            final Animation fade = new AlphaAnimation(0.0f, 1.0f);
            fade.setDuration(200);
            view.startAnimation(fade);
            progressBar.setVisibility(View.GONE);

        }
        @Override
        public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
            Toast.makeText(view.getContext(), "Authentication Error", Toast.LENGTH_LONG).show();
            // CookieManager cookieManager = CookieManager.getInstance();
            //cookieManager.setCookie(USERNAME, PASSWORD);
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public void onLoadResource( WebView view, String url ){

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

                return super.shouldOverrideUrlLoading(view, url);

        }

        @Override
        public void onReceivedHttpAuthRequest( WebView view, final HttpAuthHandler handler, final String host, final String realm ){
            // CookieManager cookieManager = CookieManager.getInstance();
            //cookieManager.setCookie(USERNAME, PASSWORD);
                handler.proceed(USERNAME,PASSWORD);

    }


         @Override
        public void onReceivedSslError( WebView view, SslErrorHandler handler, SslError error ) {
            handler.proceed();
        }

    }


   /* @Override
    public void onDetach() {
        super.onDetach();
       // mView.removeView(mWebview);
       // mWebview.removeAllViews();
        QuotesFragmentWebView.newInstanceNoBackPressed(getFragmentManager(), mSearchTerm, "goog msft", -1);
       // mWebview.destroy();
    }*/

}

Comment/Knock this out : FragmentUtils.onBackPressedKnockFragsOffStack(mainActivity, this);