samedi 23 septembre 2017

Load a url which Matches the condition in Webview of next fragment

I have 2 Fragments, Fragment 1 and Fragment 2. I am sending multiple String Url from Fragment 1 to Fragment 2 and webViw in Fragment 2 is loaded with passed url from Fragment 1.

The Code in Fragment 1 is

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
        button1 = (Button) view.findViewById(R.id.button1);
        button2 = (Button) view.findViewById(R.id.button2);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);


        return view;
    }

    @Override
    public void onClick(View v) {


        switch (v.getId()) {
            case R.id.button1:
                Fragment firstFragment = new physics();
                Bundle args = new Bundle();
                args.putString("url", "file:///android_asset/A.html");
                firstFragment.setArguments(args);
                moveToFragment(firstFragment);
                break;

            case R.id.button2:
                Fragment firstFragment1 = new physics();
                Bundle args1 = new Bundle();
                args1.putString("url1", "file:///android_asset/B.html");
                firstFragment1.setArguments(args1);
                moveToFragment(firstFragment1);
                break;

            default:
                break;


        }
    }

    private void moveToFragment(Fragment fragment) {
        getActivity().getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
    }

}

The Code in Fragment 2 is

String url = getArguments().getString("url");
        String url1 = getArguments().getString("url1");
        ;
        myWebView=(WebView)rootView.findViewById(R.id.webview);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadUrl(url);
        myWebView.loadUrl(url1);

        myWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }
        });

        myWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url1) {
                view.loadUrl(url1);
                return false;
            }
        });

It works fine but with If else statement with condition that match given url loaded in Webview will reduce size of code in Fragment 1 which I have no idea how to do this.

Any help will be Greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire