Created
July 31, 2021 11:01
-
-
Save AkaashSaini/fa6e3952714254dd6d644a4e182d5113 to your computer and use it in GitHub Desktop.
how to use webview with progressbar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//activity_main.xml | |
<?xml version="1.0" encoding="utf-8"?> | |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:app="http://schemas.android.com/apk/res-auto" | |
xmlns:tools="http://schemas.android.com/tools" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
android:orientation="vertical" | |
tools:context=".MainActivity"> | |
<ProgressBar | |
android:layout_width="match_parent" | |
android:layout_height="10dp" | |
android:id="@+id/progressbar" | |
style="?android:attr/progressBarStyleHorizontal" | |
android:progress="20" | |
android:visibility="gone"/> | |
<WebView | |
android:id="@+id/webview" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
/> | |
</LinearLayout> | |
//main.java | |
public class MainActivity extends AppCompatActivity { | |
WebView webView; | |
String url="https://www.google.co.in/"; | |
ProgressBar progressBar; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
//hide action bar | |
getSupportActionBar().hide(); | |
//connect object with activity | |
progressBar=findViewById(R.id.progressbar); | |
webView=findViewById(R.id.webview); | |
WebSettings webSettings = webView.getSettings(); | |
webSettings.setJavaScriptEnabled(true); | |
//load url to webview | |
webView.loadUrl(url); | |
//open links inside activitys | |
webView.setWebViewClient(new WebViewClient(){ | |
@Override | |
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { | |
view.loadUrl(request.getUrl().toString()); | |
return super.shouldOverrideUrlLoading(view, request); | |
} | |
}); | |
//get page loaded progress | |
webView.setWebChromeClient(new WebChromeClient(){ | |
@Override | |
public void onProgressChanged(WebView view, int newProgress) { | |
progressBar.setVisibility(View.VISIBLE); | |
progressBar.setProgress(newProgress); | |
if (newProgress==100){ | |
progressBar.setVisibility(View.GONE); | |
} | |
super.onProgressChanged(view, newProgress); | |
} | |
}); | |
} | |
//go to previous page | |
@Override | |
public void onBackPressed() { | |
if (webView.canGoBack()){ | |
webView.goBack(); | |
} | |
else{ | |
super.onBackPressed(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment