Creating Web View with Fragments - android

Im new to android and im trying to create a web View in with fragments
and i am getting an error in the Adapter class at the WebViewFragment getitem(),
Saying" THE RETURN TYPE IS INCOMPATIBLE WITH THE fragmentPagerAdapter" please help because im stuck
import homePage.HotDeals;
import homePage.NewArrivals;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.webkit.WebViewFragment;
public class HomePageAdapter extends FragmentPagerAdapter{
public HomePageAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public WebViewFragment getItem(int index) {
// TODO Auto-generated method stub
switch(index){
case 0:
return new NewArrivals();
case 1:
return new HotDeals();
}
return null;
}

Try this:
public class MainActivity extends Activity {
static public class MyWebViewFragment extends Fragment {
WebView myWebView;
final static String myBlogAddr = "http://android-er.blogspot.com";
String myUrl;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_webfragment, container, false);
myWebView = (WebView)view.findViewById(R.id.mywebview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new MyWebViewClient());
if(myUrl == null){
myUrl = myBlogAddr;
}
myWebView.loadUrl(myUrl);
return view;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
myUrl = url;
view.loadUrl(url);
return true;
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onBackPressed() {
MyWebViewFragment fragment =
(MyWebViewFragment)getFragmentManager().findFragmentById(R.id.myweb_fragment);
WebView webView = fragment.myWebView;
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
}
For further reference :
http://android-er.blogspot.in/2013/04/embed-webview-in-fragment.html
You can also use WebViewFragment.
http://developer.android.com/reference/android/webkit/WebViewFragment.html

Related

How use webview history back in a fragment?

I thought it was a very easy problem... but I haven't solved for quite some time.
For now, pressing back button will turn off the app. I want to go back by pressing the back button.
Fragment containing the webview.
HomeFragment.java
public class HomeFragment extends Fragment {
WebView webView;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
webView = view.findViewById(R.id.home_webview);
String url = "https://galaxyhub.kr/starcitizen";
webView.loadUrl(url);
webView.getSettings().setJavaScriptEnabled(true);
final ProgressDialog dialog = ProgressDialog.show(getActivity(),"", "Loading", true);
webView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
Toast.makeText(getActivity(), "URL ERROR", Toast.LENGTH_SHORT).show();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dialog.dismiss();
}
});
}
}
I heard that I should also write in the MainActivity.
I'll post it right away if needed.
package com.example.starcitizen.fragment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.starcitizen.R;
/**
* A simple {#link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
WebView webView;
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
//use this if you need to call the Activity
//backpress for default back action
requireActivity().onBackPressed();
}
}
};
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
webView = view.findViewById(R.id.home_webview);
String url = "https://galaxyhub.kr/starcitizen";
webView.loadUrl(url);
webView.getSettings().setJavaScriptEnabled(true);
final ProgressDialog dialog = ProgressDialog.show(getActivity(),"", "Loading",
true);
webView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
Toast.makeText(getActivity(), "URL ERROR", Toast.LENGTH_SHORT).show();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dialog.dismiss();
}
});
}
}
Now this code is running!
Add the fragment to the back stack if you need to navigate back from your fragment when the WebView can't go back more.
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
Then in your fragment:
public class HomeFragment extends Fragment {
private WebView webView;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
OnBackPressedCallback callback = new OnBackPressedCallback(true) {
#Override
public void handleOnBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
//use this if you need to call the Activity
//backpress for default back action
requireActivity().onBackPressed();
}
}
};
requireActivity().getOnBackPressedDispatcher()
.addCallback(getViewLifecycleOwner(), callback);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
webView = view.findViewById(R.id.home_webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
//callbacks omitted...
});
String url = "https://galaxyhub.kr/starcitizen";
//call this after WebViewClient setup
webView.loadUrl(url);
}
}
Remember that Activity on onBackPressed will be called before the one added in the Fragment.
More info on back press handling here: https://developer.android.com/guide/navigation/navigation-custom-back#java
For this to work use at least:
androidx.fragment:fragment:1.1.0

Webview with cache inside fragment

so i'm trying to do 3 fragments with differents webview each. But i cant manage to put them to work.
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Page2Fragment extends Fragment {
public Page2Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_page2, container, false);
}
}
And for the webview+cache i have this code
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
private RelativeLayout mRelativeLayout;
private WebView mWebView;
private String mUrl="https://www.google.pt";
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
mActivity = MainActivity.this;
mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
mWebView = (WebView) findViewById(R.id.web_view);
renderWebPage(mUrl);
}
protected void renderWebPage(String urlToRender) {
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Do something on page loading started
}
#Override
public void onPageFinished(WebView view, String url) {
// Do something when page loading finished
});
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int newProgress) {
}
});
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setAppCachePath(mContext.getCacheDir().getPath());
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
mWebView.loadUrl(urlToRender);
}
}`
I can put the code to work alone, in another app, but not with fragments.
With a simple webview it's ok too,but i really want to "cache" the website or display an error message saying that the internet is not on.

Can't change TextView in Fragment from main Activity( with interface),

Although i have read similar post-questions, i havent found solution to my problem. As you can see in the title i cant change Textview in TextFragment.
i get this error:07-09 15:05:55.593 6441-6441/com.eguide.dimitris.campusguide E/AndroidRuntime: FATAL EXCEPTION: main
07-09 15:05:55.593 6441-6441/com.eguide.dimitris.campusguide E/AndroidRuntime: java.lang.NullPointerException
07-09 15:05:55.593 6441-6441/com.eguide.dimitris.campusguide E/AndroidRuntime: at com.eguide.dimitris.campusguide.mainActivity$1.onVisitStart(mainActivity.java:66)
So i would appreciate any help.
Thanks in advance.
mainActivity
public class mainActivity extends Activity implements inter {
public PlaceManager placeManager;
public PlaceEventListener placeEventListener;
public String name;
TextView tt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Gimbal.setApiKey(this.getApplication(), "5436462c-6400-48f4-b6af-e0ad2094550f");
CommunicationManager.getInstance().startReceivingCommunications();
tt=(TextView) findViewById(R.id.test);
}
#Override
public void respond(String data) {
FragmentManager manager2=getFragmentManager();
textFragment frag2= (textFragment) manager2.findFragmentById(R.id.text_fragment);
frag2.changeText(data);
}
#Override
public void barstatus() {
FragmentManager manager1=getFragmentManager();
imageFragment frag1=(imageFragment) manager1.findFragmentById(R.id.image_fragment);
frag1.changeStatus();
}
#Override
public void barstatus2() {
FragmentManager manager1=getFragmentManager();
imageFragment frag1=(imageFragment) manager1.findFragmentById(R.id.image_fragment);
frag1.changeStatus2();
}
public void changestatus(){
placeEventListener= new PlaceEventListener() {
#Override
public void onVisitStart(Visit visit) {
super.onVisitStart(visit);
name=visit.getPlace().getName().toString();
if (name!=null){
respond(name);
barstatus2();
}
}
};
textFragment
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class textFragment extends Fragment {
TextView text1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.text_fragment, container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
text1 = (TextView)getActivity().findViewById(R.id.textF);
text1.setText("Press Start button to find buildings near you");
}
public void changeText(String data){
text1 = (TextView)getActivity().findViewById(R.id.textF);
text1.setText(data.toString());
}
}
imageFragment
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.transition.Visibility;
import android.view.ActionProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
public class imageFragment extends Fragment {
private ProgressBar bar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.image_fragment,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
bar=(ProgressBar) getActivity().findViewById(R.id.progressBar);
bar.setVisibility(View.INVISIBLE);
}
public void changeStatus(){
bar=(ProgressBar) getActivity().findViewById(R.id.progressBar);
bar.setVisibility(View.VISIBLE);
}
public void changeStatus2(){
bar=(ProgressBar) getActivity().findViewById(R.id.progressBar);
bar.setVisibility(View.INVISIBLE);
}
}
interface
public interface inter {
public void respond(String data);
public void barstatus();
public void barstatus2();
}
Guys also note tha i have tried and this in mainActivity but nothing changed.
inter inte;
public void changestatus(){
placeEventListener= new PlaceEventListener() {
#Override
public void onVisitStart(Visit visit) {
super.onVisitStart(visit);
name=visit.getPlace().getName().toString();
if (name!=null){
inte.respond(name);
inte.barstatus2();
}
}
};
EDIT:
if instead of
public void changestatus(){
placeEventListener= new PlaceEventListener() {
#Override
public void onVisitStart(Visit visit) {
super.onVisitStart(visit);
name=visit.getPlace().getName().toString();
if (name!=null){
respond(name);
barstatus2();
}
}
use
#Override
protected void onStart() {
super.onStart();
placeEventListener= new PlaceEventListener() {
#Override
public void onVisitStart(Visit visit) {
super.onVisitStart(visit);
name=visit.getPlace().getName();
if (name!=null){
respond(name);
barstatus2();
}
}
};
i can make changes...can you explain me why??
i dont want this block of code running onStart().
i want this block of code working inside a method.
You need to make little change in your textFragment, initialize TextView in onCreateView() method as,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.text_fragment, container,false);
text1 = (TextView)getActivity().findViewById(R.id.textF);
text1.setText("Press Start button to find buildings near you");
return view;
}

View.onRestoreInstanceState not being called when fragment setRetainInstance(true) (double screen orientation change when fragment is in a back stack)

I have two fragments: one on top of another. Fragments has setRetainInstance(true) in their constructors.
When I do a double screen flip and press back key, top fragment gets popped and bottom fragment becomes visible. But bottom fragment's view do not receive onRestoreInstanceState.
When I remove setRetainInstance(true) everything works just fine. But I need that setRetainInstance(true) to work with multiple threads, so I can't solve my problem that simple. :)
How to guarantee onRestoreInstanceState to be called in this case?
Here is some example code:
package com.example.saverestoreviewstate;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().replace(android.R.id.content, new Fragment1()).commit();
}
}
public static class SaveRestoreView extends TextView {
public SaveRestoreView(Context context) {
super(context);
}
String value;
public void setValue(String value) {
this.value = value;
setText(value);
}
#Override
public Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable("super", super.onSaveInstanceState());
bundle.putString("value", value);
return bundle;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
Bundle bundle = (Bundle)state;
super.onRestoreInstanceState(bundle.getParcelable("super"));
value = bundle.getString("value");
setText(value);
}
}
public static class Fragment1 extends Fragment {
private static boolean firstRun = true;
public Fragment1() {
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Context context = inflater.getContext();
LinearLayout layout = new LinearLayout(context);
layout.setId(12);
layout.setOrientation(LinearLayout.VERTICAL);
SaveRestoreView saveRestore = new SaveRestoreView(context);
saveRestore.setId(128);
if (firstRun) {
saveRestore.setValue("*******save this string*******");
firstRun = false;
}
layout.addView(saveRestore);
Button button = new Button(inflater.getContext());
button.setText("Create 2nd fragment");
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(android.R.id.content, new Fragment2()).addToBackStack(null).commit();
}
});
layout.addView(button);
return layout;
}
}
public static class Fragment2 extends Fragment {
public Fragment2() {
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return new View(inflater.getContext());
}
}
}
So, I've finished implementing save/restore logic manually.
The minus is that I can't turn off save\restore that already exist, so onSaveInstance/onRestoreInstance is called twice on a View. Except of that one time when it is not called by itself - then it IS called once B-).
To make it work just add to Fragment1 class:
SparseArray<Parcelable> savedState;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedState != null)
view.restoreHierarchyState(savedState);
}
#Override
public void onDestroyView() {
super.onDestroyView();
savedState = new SparseArray<Parcelable>();
getView().saveHierarchyState(savedState);
}

Web View Fragment html embeed video fullscreen suport

Hello everyone i got a question regarding how to enable full screen support in html embed videos on my webview i have hardware accelerated true on manifest and the video works ok but wen pressed to go fullscreen the video stops.
here is my code
import com.photoshop.video.tutorials.R;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class WebViewFragment extends Fragment {
public final static String TAG = WebViewFragment.class.getSimpleName();
private WebView viewContentWebView;
private String url;
private boolean resetHistory = true;
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.webview, container, false);
final ProgressBar viewContentProgress = (ProgressBar) v.findViewById(R.id.progress);
viewContentWebView = (WebView) v.findViewById(R.id.webview);
viewContentWebView.getSettings().setJavaScriptEnabled(true);
viewContentWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
viewContentWebView.loadUrl("file:///android_asset/myerrorpage.html");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
});
viewContentWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
viewContentProgress.setProgress(newProgress);
viewContentProgress.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE);
if (newProgress == 100 && resetHistory) {
viewContentWebView.clearHistory();
resetHistory = false;
}
}
});
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
reload();
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden)
viewContentWebView.stopLoading();
else
reload();
}
public void setUrl(String url) {
this.url = url;
if (viewContentWebView != null)
viewContentWebView.stopLoading();
resetHistory = true;
}
public void reload() {
if (TextUtils.isEmpty(url))
return;
viewContentWebView.loadUrl(url);
}
public boolean onBackPressed() {
if (viewContentWebView.canGoBack()) {
viewContentWebView.goBack();
return true;
}
return false;
}
}
How can i achieve this
many thanks in advance and a little patience with me because i am very very VERY new to android
You should override the two following methods in your WebChromeClient:
public void onShowCustomView(View view, CustomViewCallback callback);
public void onHideCustomView();
This is an extract of the code I'm using:
private View mCustomView;
private class MyWebChromeClient extends WebChromeClient {
private int mOriginalOrientation;
private FullscreenHolder mFullscreenContainer;
private CustomViewCallback mCustomViewCollback;
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mOriginalOrientation = mActivity.getRequestedOrientation();
FrameLayout decor = (FrameLayout) mActivity.getWindow().getDecorView();
mFullscreenContainer = new FullscreenHolder(mActivity);
mFullscreenContainer.addView(view, ViewGroup.LayoutParams.MATCH_PARENT);
decor.addView(mFullscreenContainer, ViewGroup.LayoutParams.MATCH_PARENT);
mCustomView = view;
mCustomViewCollback = callback;
mActivity.setRequestedOrientation(mOriginalOrientation);
}
#Override
public void onHideCustomView() {
if (mCustomView == null) {
return;
}
FrameLayout decor = (FrameLayout) mActivity.getWindow().getDecorView();
decor.removeView(mFullscreenContainer);
mFullscreenContainer = null;
mCustomView = null;
mCustomViewCollback.onCustomViewHidden();
// show the content view.
mActivity.setRequestedOrientation(mOriginalOrientation);
}
static class FullscreenHolder extends FrameLayout {
public FullscreenHolder(Context ctx) {
super(ctx);
setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
}
#Override
public boolean onTouchEvent(MotionEvent evt) {
return true;
}
}

Categories

Resources