calling intent WebView in fragment

时间:2018-03-25 19:06:43

标签: android android-fragments android-intent webview

Hi I'm trying to call a webview fragment when an item of recyclerview is clicked, I made a fragment with it's layout for the webview, and I have an adapter to call the fragment but it shuts down the APP:

public class WebViewFragment extends Fragment {

    public WebView mWebView;


    public WebViewFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        mWebView = (WebView) mWebView.findViewById(R.id.webview);
        mWebView.loadUrl("google.com");

        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // Force links and redirects to open in the WebView instead of in a browser
        mWebView.setWebViewClient(new WebViewClient());

        return inflater.inflate(R.layout.fragment_web_view, container, false);
    }

}

And the adapter:

@Override
    public void onClick(View view) {
        int position = (int) view.getTag();
        News news =newsItems.get(position);
        Uri uri = Uri.parse(news.getLink());
        Intent intent = new Intent(mACtivity, WebViewFragment.class);
        mACtivity.startActivity(intent);

    }

Layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="tech.amro.amro.WebViewFragment">

    <!-- TODO: Update blank fragment layout -->

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/webview"/>

</FrameLayout>

I know I'm not sending the url to the webview yet but I'm just testing to load the view first then sending the url. but when the item is clicked it shuts down the APP. and gives this error:

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: tech.amro.amro, PID: 18958
                  android.content.ActivityNotFoundException: Unable to find explicit activity class {tech.amro.amro/tech.amro.amro.WebViewFragment}; have you declared this activity in your AndroidManifest.xml?
                      at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1932)
                      at android.app.Instrumentation.execStartActivity(Instrumentation.java:1615)
                      at android.app.Activity.startActivityForResult(Activity.java:4472)
                      at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
                      at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
                      at android.app.Activity.startActivityForResult(Activity.java:4430)
                      at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:720)
                      at android.app.Activity.startActivity(Activity.java:4791)
                      at android.app.Activity.startActivity(Activity.java:4759)
                      at tech.amro.amro.adapters.NewsAdapter.onClick(NewsAdapter.java:73)
                      at android.view.View.performClick(View.java:6256)
                      at android.view.View$PerformClick.run(View.java:24701)
                      at android.os.Handler.handleCallback(Handler.java:789)
                      at android.os.Handler.dispatchMessage(Handler.java:98)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Application terminated.

1 个答案:

答案 0 :(得分:0)

If you don't have a specific reason to use a WebView you could just use an Intent to start a web browser as follows.

@Override
public void onClick(View view) {
    int position = (int) view.getTag();
    News news = newsItems.get(position);
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(news.getLink()));
    startActivity(i);
}

Note you probably would need to check if the device can handle the URI - some people might not have a browser installed which will result in an ActivityNotFoundException.

If you do need to use the WebView you have a couple of issues:

Fragments can't be started the same way you start an activity, to display a fragment you need to use the FragmentManager in order to add it into your Activity.

Regarding your Fragment, the onCreateView code won't work. You need to inflate the xml first that contains your webview and then find the webview from that layout. At the moment you're trying to find the webView from the webView which will result in a NullPointerException. You should also prefer onViewCreated to find and load the WebView url.

Your fragment should probably look something like the following

public class WebViewFragment extends Fragment {

    private static final String NEWS_LINK_KEY = "NEWS_LINK";
    private String newsLink;

    public static WebViewFragment newInstance(String uri) {
        Bundle args = new Bundle();
        args.putString(NEWS_LINK_KEY, uri);
        WebViewFragment webViewFragment = new WebViewFragment();
        webViewFragment.setArguments(args);
        return webViewFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        newsLink = this.getArguments().getString(NEWS_LINK_KEY);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.web_view, container, false)
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        WebView webView = (WebView) view.findViewById(R.id.webview);

        // Enable Javascript
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // Force links and redirects to open in the WebView instead of in a browser
        webView.setWebViewClient(new WebViewClient());

        webView.loadUrl(newsLink);
    }
}

This could be started from the onClick method as follows:

@Override
public void onClick(View view) {
    int position = (int) view.getTag();
    News news = newsItems.get(position);
    getSupportFragmentManager().beginTransaction()
            .add(android.R.id.content, WebViewFragment.newInstance(news.getLink()))
            .commit();
}