Android How to make full screen Video? - android

When I make a video full screen in WebView, the toolbar is not hidden. How can I hide it? Below you can see the codes I use.I'm using fragment and the navigation drawer menu.
When I make a video full screen in WebView, the toolbar is not hidden. How can I hide it? Below you can see the codes I use.I'm using fragment and the navigation drawer menu.
Full screen
public class searchWebFragment extends Fragment {
public searchWebFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.searchwb, container, false);
final ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.progressBarHome);
final WebView webView = (WebView) v.findViewById(R.id.wv_home);
final EditText araTxt = (EditText)v.findViewById(R.id.araTxt);
final Button araBtn = (Button)v.findViewById(R.id.araBtn);
final TextView uyariTxt = (TextView)v.findViewById(R.id.uyariTxt);
progressBar.setVisibility(View.INVISIBLE);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int i, String s, String d1) {
webView.loadUrl("file:///android_asset/error.html");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.INVISIBLE);
}
});
webView.getSettings().setBuiltInZoomControls(true);
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, url);
DownloadManager dm = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getActivity().getApplicationContext(), "Dosya Ä°ndiriliyor", //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();
}
});
webView.setVisibility(View.INVISIBLE);
araBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
webView.setVisibility(View.VISIBLE);
String aranacaksey = araTxt.getText().toString();
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
String url = "http://www.ifsalar.16mb.com/?s=" + aranacaksey;
webView.loadUrl(url);
araTxt.setVisibility(View.INVISIBLE);
araBtn.setVisibility(View.INVISIBLE);
uyariTxt.setVisibility(View.INVISIBLE);
}
});
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();
}
return true;
}
return false;
}
});
return v;
}
}

I would recommend you to try out the follow code and remove the listeners which are related to loading the contents of your WebView.
You need to implement the method to load the website in your webview first.
private void loadWebsite() {
ConnectivityManager connectivityManager = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager .getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
mWebView.loadUrl("yourURL");
} else {
mWebView.setVisibility(View.GONE);
}
}
From here, you need to implement 2 different class "Browser_Home" and "MyChrome". For testing purposes, just write it outside searchWebFragment and later on you can implement it as a separate java file. With only the Browser_Home class, the fullscreen button will be disabled. When MyChrome class is added, fullscreen button is enabled and toolbar should disappear as intended.
class Browser_home extends WebViewClient {
Browser_home() {
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
setTitle(view.getTitle());
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
private class MyChrome extends WebChromeClient {
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
protected FrameLayout mFullscreenContainer;
private int mOriginalOrientation;
private int mOriginalSystemUiVisibility;
MyChrome() {}
public Bitmap getDefaultVideoPoster()
{
if (mCustomView == null) {
return null;
}
return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
}
public void onHideCustomView()
{
((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
this.mCustomView = null;
getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
setRequestedOrientation(this.mOriginalOrientation);
this.mCustomViewCallback.onCustomViewHidden();
this.mCustomViewCallback = null;
}
public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
{
if (this.mCustomView != null)
{
onHideCustomView();
return;
}
this.mCustomView = paramView;
this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
this.mOriginalOrientation = getRequestedOrientation();
this.mCustomViewCallback = paramCustomViewCallback;
((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
getWindow().getDecorView().setSystemUiVisibility(3846);
}
}
And finally, apply the following functions and attributes to your webview and give it another try. Remember to apply these within your OnCreate method:
mWebView.setWebViewClient(new Browser_home());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
loadWebsite();
Let me know if this works and I can credit the corresponding person for the assistance with the code and classes.

create a folder row and copy the video on raw folder on resources and do the following steps,
On your XML file add VideoView,
<VideoView
android:id="#+id/vdoPlayer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"/>
On your .java class file do,
Uri uri = Uri.parse("android.resource://Your package name Here/" + R.raw.welcome_video);
vdoPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
vdoPlayer.setVideoURI(uri);
vdoPlayer.start();

Related

how to save images in fragment in webview on long presson the image

hi guys i want that user can save images(which are displayed inside fragment webview) to there gallery.I want that user will able to save image to there gallery which is displayed in webview. i checked the internet but non of the code work for me. can you give me a complete working code according to my fragment code . im new to android studio and a 10th grade student pls help me
public class BlankFragment extends Fragment {
public Handler h;
ProgressBar progressBar;
public AdView adView;
public WebView mWebView;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
public BlankFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view
= inflater.inflate(R.layout.fragment_blank, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setMax(100);
progressBar.setProgress(1);
mWebView = (WebView) view.findViewById(R.id.hu);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setVerticalScrollBarEnabled(true);
mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setHorizontalScrollBarEnabled(true);
this.mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.loadUrl("https://stockphoto.com/search.php?q=poo+emoji");
mWebView.setOnKeyListener(new View.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return false;
}
}); mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
});
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
}
});
return view;
}
}
You have to decode HTML:
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
After that get Image Tag from it then you can get mages from it and write to sd card.

Android download file with webview

I have app's MainActivity like this, and this app can't download file with webview
Anybody knows how to fix the download problem?
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Webkit;
namespace REC
{
[Activity(Label = "APPNAME", MainLauncher = true, Icon = "#drawable/rec512", ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
public class MainActivity : Activity
{
private WebView mWebView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
RequestWindowFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Main);
mWebView = FindViewById<WebView>(Resource.Id.webview);
mWebView.Settings.SetRenderPriority(WebSettings.RenderPriority.High);
mWebView.Settings.JavaScriptEnabled = true;
mWebView.LoadUrl("http://www.APPname.com");
mWebView.SetWebViewClient(new WebViewClient());
// mWebView.SetDownloadListener(new MyDownloadListener()
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = (WebRequest)base.GetWebRequest(address);
// Perform any customizations on the request.
// This version of WebClient always preauthenticates.
request.PreAuthenticate = true;
return request;
}
class MonkeyWebChromeClient : WebChromeClient
{
public override bool OnJsAlert(WebView view, string url, string message, JsResult result)
{
return base.OnJsAlert(view, url, message, result);
}
public override Boolean OnJsConfirm(WebView view, String url, String message, JsResult result)
{
return base.OnJsConfirm(view, url, message, result);
}
public override Boolean OnJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result)
{
return base.OnJsPrompt(view, url, message, defaultValue, result);
}
}
public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back && mWebView.CanGoBack())
{
mWebView.GoBack();
return true;
}
return base.OnKeyDown(keyCode, e);
}
}
public class WebClient : WebViewClient
{
public override bool ShouldOverrideUrlLoading(WebView view, string url)
{
//return base.ShouldOverrideUrlLoading(view, url);
view.LoadUrl(url);
return true;
}
internal object GetWebRequest(Uri address)
{
throw new NotImplementedException();
}
}
}
You did not implement webview download listener,please refer to the following code :
public class MainActivity : Activity
{
WebView wv1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
wv1 = FindViewById<WebView>(Resource.Id.webView1);
wv1.SetDownloadListener(new MyDownloadListerner(this));
wv1.LoadUrl("https://notepad-plus-plus.org/download/v7.3.2.html");
}
class MyDownloadListerner : Java.Lang.Object, IDownloadListener
{
Context cont;
public MyDownloadListerner(Context context)
{
cont = context;
}
public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
{
Android.Net.Uri uri = Android.Net.Uri.Parse(url);
Intent intent = new Intent(Intent.ActionView,uri);
cont.StartActivity(intent);
}
}
}
Note: This method is start another browser to download, you can also create a new thread to download file at the OnDownloadStart function.
screen shot:
Please follow the following code
public class WebViewFragment extends KaROFragment {
private WebView mWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_webview, container, false);
try {
mWebView = (WebView) view.findViewById(R.id.webView);
mWebView.setWebViewClient(new myWebClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.loadUrl("https://www.google.com/");
} catch (Exception e) {
e.getStackTrace();
}
return view;
}
public class myWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
public void downloadAndPrintDocument(WebView webView, String title) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);
//noinspection deprecation
PrintDocumentAdapter printDocumentAdapter = webView.createPrintDocumentAdapter();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
printDocumentAdapter = webView.createPrintDocumentAdapter(title);
String documentName = title;
PrintJob printJob = printManager.print(documentName, printDocumentAdapter, new PrintAttributes.Builder().build());
List<PrintJob> printJobs = printManager.getPrintJobs();
printJobs.add(printJob);
} else {
// mContext.showToast(mContext.getString(R.string.mytools_printing_not_supported), 1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

How can i block or avoid popup in webview?

the webpage have some popup ads is there any way to prevent the popup from loading when the popup loads the main site doesnt appears is there any way to load the main page with out popups and how can i add a download handler l mean the webview should support downloading .torrent file
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ProgressBar progressBar;
private LinearLayout layoutProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
layoutProgress = (LinearLayout) findViewById(R.id.layoutProgress);
webView.setVisibility(View.GONE);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
settings.setSupportZoom(true);
settings.setDisplayZoomControls(false);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
webView.setVisibility(View.VISIBLE);
layoutProgress.setVisibility(View.GONE);
progressBar.setIndeterminate(false);
super.onPageFinished(view, url);
}
public void but(View v){
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layoutProgress.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
super.onPageStarted(view, url, favicon);
}
});
if(isOnline()) {
webView.loadUrl("http://testsite.com/");
} else {
String summary = "<html><body><font color='red'>No Internet Connection</font></body></html>";
webView.loadData(summary, "text/html", null);
toast("No Internet Connection.");
}
}
private void toast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
public void but(View v){
webView.loadUrl("http://testsite.com/");
}
}
if the url changes then use shouldOverrideUrlLoading with some regex
so
List<String> validUrls = new LinkedList<>();
validUrls.add("https://www\\.google\\.com/*");
validUrls.add("https://www\\.facebook\\.com/*");
#Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (isValidUrl(url)) {
return false;
}
return true;
}
private boolean isValidUrl(String url) {
for (String validUrl : validUrls) {
Pattern pattern = Pattern.compile(validUrl, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
return true;
}
}
return false;
}
would match against any www.google.com or facebook.com urls
You can intercept the urls that are opened from the webview, I don't know if it would work with the popup:
WebViewClient client= new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if (url.equals("popupURL"){
return true;
}
return false;
}
}
webView.setWebViewClient(client);

WebChromeClient not working Android

I got a progress bar, a Full screen video playback method (for playing youtube videos in full-screen), and public boolean shouldOverrideUrlLoading for handling URL's within the WebView but i cannot get all of the three to work together, i tried the following three approaches and it seems like i need duplicate webviewClient and webChromeclients to make everything work which depend on them
Approach 1 - Progress Bar is not working (stuck on 0%)
public class MainActivity extends Activity {
private WebView mWebView;
private EditText urlEditText;
private ProgressBar progress;
// FULL-SCREEN VIDEO-1
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
// FULL-SCREEN VIDEO-1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FULL-SCREEN VIDEO-2
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#Override
public void onShowCustomView(View view,
WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new
// one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
// FULL-SCREEN VIDEO-2
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
// Download manager
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
// **//
// URL BAR AND PROGRESS BAR
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
urlEditText = (EditText) findViewById(R.id.urlField);
// Use Done/search button in keyboard as go button
urlEditText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// Toast.makeText(getApplicationContext(), "some key pressed",
// Toast.LENGTH_LONG).show();
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
|| url.endsWith(".ad") || url.endsWith(".zw")) {
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
} else
url = "https://www.google.com/search?q="
+ url.replace(" ", "+");// Prefix (replace spaces
// with a '+' sign)
mWebView.loadUrl(url);
if (validateUrl(url)) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
return false;
}
private boolean validateUrl(String url) {
return true;
}
});
// **//
}
private class MyWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.setWebChromeClient(mWebChromeClient);
webview.loadUrl(url);
return true;
}
}
// FULL-SCREEN VIDEO-3
#Override
protected void onStop() {// plays video outside frame on back button and
// prevents from going back
super.onStop();
if (mCustomView != null) {
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {// hide custom view (in which the video plays)
// on back button
super.onBackPressed();
if (mCustomView != null) {
mWebChromeClient.onHideCustomView();
} else {
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {// prevents the
// custom view from
// running in
// background when
// app is closed
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
// FULL-SCREEN VIDEO-3
}
}
Approach 2 - Full Screen Not working
public class MainActivity extends Activity {
private WebView mWebView;
private EditText urlEditText;
private ProgressBar progress;
// FULL-SCREEN VIDEO-1
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
// FULL-SCREEN VIDEO-1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FULL-SCREEN VIDEO-2
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#Override
public void onShowCustomView(View view,
WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new
// one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
// FULL-SCREEN VIDEO-2
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.setWebChromeClient(new mWebChromeClient());
// Download manager
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
// **//
// URL BAR AND PROGRESS BAR
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
urlEditText = (EditText) findViewById(R.id.urlField);
// Use Done/search button in keyboard as go button
urlEditText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// Toast.makeText(getApplicationContext(), "some key pressed",
// Toast.LENGTH_LONG).show();
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
|| url.endsWith(".ad") || url.endsWith(".zw")) {
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
} else
url = "https://www.google.com/search?q="
+ url.replace(" ", "+");// Prefix (replace spaces
// with a '+' sign)
mWebView.loadUrl(url);
if (validateUrl(url)) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
return false;
}
private boolean validateUrl(String url) {
return true;
}
});
// **//
}
private class mWebChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.loadUrl(url);
return true;
}
}
// FULL-SCREEN VIDEO-3
#Override
protected void onStop() {// plays video outside frame on back button and
// prevents from going back
super.onStop();
if (mCustomView != null) {
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {// hide custom view (in which the video plays)
// on back button
super.onBackPressed();
if (mCustomView != null) {
mWebChromeClient.onHideCustomView();
} else {
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {// prevents the
// custom view from
// running in
// background when
// app is closed
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
// FULL-SCREEN VIDEO-3
}
}
Approach 3 - shouldOverrideUrlLoading not working
public class MainActivity extends Activity {
private WebView mWebView;
private EditText urlEditText;
private ProgressBar progress;
// FULL-SCREEN VIDEO-1
private LinearLayout mContentView;
private FrameLayout mCustomViewContainer;
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
private WebChromeClient mWebChromeClient;
// FULL-SCREEN VIDEO-1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// FULL-SCREEN VIDEO-2
mContentView = (LinearLayout) findViewById(R.id.linearlayout);
mWebView = (WebView) findViewById(R.id.webView);
mCustomViewContainer = (FrameLayout) findViewById(R.id.fullscreen_custom_content);
mWebChromeClient = new WebChromeClient() {
#Override
public void onShowCustomView(View view,
WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new
// one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Add the custom view to its container.
mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
mCustomView = view;
mCustomViewCallback = callback;
// hide main browser view
mContentView.setVisibility(View.GONE);
// Finally show the custom view container.
mCustomViewContainer.setVisibility(View.VISIBLE);
mCustomViewContainer.bringToFront();
}
#Override
public void onHideCustomView() {
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
};
// FULL-SCREEN VIDEO-2
WebSettings webSettings = mWebView.getSettings();
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebChromeClient(new HelloWebViewClient());
// Download manager
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "download");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
// **//
// URL BAR AND PROGRESS BAR
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
urlEditText = (EditText) findViewById(R.id.urlField);
// Use Done/search button in keyboard as go button
urlEditText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
// Toast.makeText(getApplicationContext(), "some key pressed",
// Toast.LENGTH_LONG).show();
String url = urlEditText.getText().toString();
if (url.endsWith(".ac") || url.endsWith(".ac.uk")
|| url.endsWith(".ad") || url.endsWith(".zw")) {
if (!url.startsWith("http://")
&& !url.startsWith("https://")) {
url = "http://" + url;
}
} else
url = "https://www.google.com/search?q="
+ url.replace(" ", "+");// Prefix (replace spaces
// with a '+' sign)
mWebView.loadUrl(url);
if (validateUrl(url)) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
MainActivity.this.progress.setProgress(10);
}
return false;
}
private boolean validateUrl(String url) {
return true;
}
});
// **//
}
private class HelloWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
private class HelloWebViewClient1 extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
webview.setWebChromeClient(mWebChromeClient);
webview.loadUrl(url);
return true;
}
}
// FULL-SCREEN VIDEO-3
#Override
protected void onStop() {// plays video outside frame on back button and
// prevents from going back
super.onStop();
if (mCustomView != null) {
if (mCustomViewCallback != null)
mCustomViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
#Override
public void onBackPressed() {// hide custom view (in which the video plays)
// on back button
super.onBackPressed();
if (mCustomView != null) {
mWebChromeClient.onHideCustomView();
} else {
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {// prevents the
// custom view from
// running in
// background when
// app is closed
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
// FULL-SCREEN VIDEO-3
}
}

adding custom progress bar in android webview

I need a progress bar at the centre of my android webview it must be shown before the page loads and hides when the page is loaded. How can it be done? Can anyone help me?
This is my code for webview:
Bundle extras = getIntent().getExtras();
String title;
final String url;
if (!Datacon.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "Check your Internet Connection!", Toast.LENGTH_LONG).show();
} else {
if (extras != null) {
title = extras.getString("title");
url = extras.getString("url");
TextView text=(TextView) findViewById(R.id.textView1);
text.setText(title);
final WebView myWebView =(WebView)findViewById(R.id.WebView);
myWebView.loadUrl(url);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
loadingProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal);
myWebView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
Button refresh = (Button) actionBar.getCustomView().findViewById(R.id.but2);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myWebView.loadUrl(url);
}
});
}
}}
}
You need to override a couple of more methods in the WebViewClient :
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
loadingProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
loadingProgressBar.setVisibility(View.GONE);
}
I'm assuming loadingProgressBar is a class field.
PS: As a side note I believe you overriding shouldOverrideUrlLoading is unnecessary. The default behaviour is to load the url, as you instruct it to do.
private void initializeProgressBar() {
if (progressBar == null){
progressBar = new ProgressDialog(this);
progressBar.setMessage(Constants.LOADING_MESSAGE);
progressBar.setCancelable(false);
}
}
Handler peogressBar = new Handler(){
public void handleMessage(android.os.Message msg) {
try{
switch (msg.what) {
case 1:
initializeProgressBar();
if(!progressBar.isShowing())
progressBar.show();
break;
case 2:
if (progressBar != null && progressBar.isShowing()) {
progressBar.dismiss();
progressBar = null;
}
break;
}
}catch(Exception e){
e.printStackTrace();
}
};
};
wv_graphLink = (WebView) findViewById(R.id.wv_graphLink);
wv_graphLink.getSettings().setJavaScriptEnabled(true);
wv_graphLink.getSettings().setBuiltInZoomControls(true);
wv_graphLink.getSettings().setSupportZoom(true);
wv_graphLink.setInitialScale(1);
wv_graphLink.getSettings().setLoadWithOverviewMode(true);
wv_graphLink.getSettings().setUseWideViewPort(true);
// wv_graphLink.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
// wv_graphLink.setScrollbarFadingEnabled(false);
peogressBar.sendEmptyMessage(1);
wv_graphLink.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress) {
if(progress == 100){
peogressBar.sendEmptyMessage(2);
}
}
});
wv_graphLink.loadUrl("Your url");

Categories

Resources