0

我在片段容器中有一个 webview,我在其中嵌入了后退功能。它适用于使用设备后退按钮在 web 视图中进行导航。但是,当我单击设备返回按钮退出片段时说我打开包含新闻的片段 1,然后打开包含此 web 视图的片段 2,然后单击设备返回按钮返回新闻片段,它不起作用,它必须返回到应用程序的主页。这是我正在使用的代码类。我不知道该怎么做,我是否必须编辑一些 backpressed() 函数?如果是这样,我该怎么做,或者有一种方法可以创建 if(goingback),返回 -1 以返回 1 步。有任何想法吗?

谢谢!贾斯汀

@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();
    }*/

}
4

1 回答 1

0

评论/取消这个:FragmentUtils.onBackPressedKnockFragsOffStack(mainActivity, this);

于 2013-10-04T17:22:53.900 回答