SHOW:
|
|
- or go back to the newest paste.
1 | public class ImprovedWebViewFragment extends Fragment { | |
2 | ||
3 | private WebView mWebView; | |
4 | private boolean mIsWebViewAvailable; | |
5 | private String mUrl = null; | |
6 | ||
7 | - | public ImprovedWebViewFragment() { |
7 | + | |
8 | * Creates a new fragment which loads the supplied url as soon as it can | |
9 | * @param url the url to load once initialised | |
10 | */ | |
11 | public ImprovedWebViewFragment(String url) { | |
12 | super(); | |
13 | mUrl = url; | |
14 | } | |
15 | ||
16 | /** | |
17 | * Called to instantiate the view. Creates and returns the WebView. | |
18 | */ | |
19 | @Override | |
20 | public View onCreateView(LayoutInflater inflater, ViewGroup container, | |
21 | Bundle savedInstanceState) { | |
22 | if (mWebView != null) { | |
23 | mWebView.destroy(); | |
24 | } | |
25 | mWebView = new WebView(getActivity()); | |
26 | mWebView.loadUrl(mUrl); | |
27 | mIsWebViewAvailable = true; | |
28 | return mWebView; | |
29 | } | |
30 | ||
31 | /** | |
32 | * Convenience method for loading a url. Will fail if {@link View} is not initialised (but won't throw an {@link Exception}) | |
33 | * @param url | |
34 | */ | |
35 | public void loadUrl(String url) { | |
36 | if (mIsWebViewAvailable) getWebView().loadUrl(mUrl = url); | |
37 | else Log.w("ImprovedWebViewFragment", "WebView cannot be found. Check the view and fragment have been loaded."); | |
38 | } | |
39 | ||
40 | /** | |
41 | * Called when the fragment is visible to the user and actively running. Resumes the WebView. | |
42 | */ | |
43 | @Override | |
44 | public void onPause() { | |
45 | super.onPause(); | |
46 | mWebView.onPause(); | |
47 | } | |
48 | ||
49 | /** | |
50 | * Called when the fragment is no longer resumed. Pauses the WebView. | |
51 | */ | |
52 | @Override | |
53 | public void onResume() { | |
54 | mWebView.onResume(); | |
55 | super.onResume(); | |
56 | } | |
57 | ||
58 | /** | |
59 | * Called when the WebView has been detached from the fragment. | |
60 | * The WebView is no longer available after this time. | |
61 | */ | |
62 | @Override | |
63 | public void onDestroyView() { | |
64 | mIsWebViewAvailable = false; | |
65 | super.onDestroyView(); | |
66 | } | |
67 | ||
68 | /** | |
69 | * Called when the fragment is no longer in use. Destroys the internal state of the WebView. | |
70 | */ | |
71 | @Override | |
72 | public void onDestroy() { | |
73 | if (mWebView != null) { | |
74 | mWebView.destroy(); | |
75 | mWebView = null; | |
76 | } | |
77 | super.onDestroy(); | |
78 | } | |
79 | ||
80 | /** | |
81 | * Gets the WebView. | |
82 | */ | |
83 | public WebView getWebView() { | |
84 | return mIsWebViewAvailable ? mWebView : null; | |
85 | } | |
86 | ||
87 | } |