Created
September 27, 2021 11:54
-
-
Save anta40/8691c1c271e8e3a96f9eeaa5b7ae7250 to your computer and use it in GitHub Desktop.
Load random URL if webview is refreshed
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
package com.anta40.webviewtest; | |
import androidx.appcompat.app.AppCompatActivity; | |
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; | |
import android.os.Bundle; | |
import android.webkit.WebSettings; | |
import android.webkit.WebView; | |
import android.webkit.WebViewClient; | |
import java.util.Random; | |
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener { | |
private WebView webView; | |
private SwipeRefreshLayout swipeRefreshLayout; | |
private String[] randomUrls; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
randomUrls = new String[]{"https://www.codepolitan.com","https://www.detik.com", | |
"https://www.apple.com", "https://en.wikipedia.org/wiki/Main_Page"}; | |
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh); | |
swipeRefreshLayout.setOnRefreshListener(this); | |
webView = (WebView) findViewById(R.id.webview); | |
webView.setWebViewClient(new CustomWebViewClient()); | |
WebSettings webSettings = webView.getSettings(); | |
webSettings.setJavaScriptEnabled(true); | |
webView.loadUrl(randomUrls[getRandomIndex(0,4)]); | |
} | |
@Override | |
public void onRefresh() { | |
String url = randomUrls[getRandomIndex(0, 3)]; | |
webView.loadUrl(url); | |
} | |
public int getRandomIndex(int min, int max) { | |
Random random = new Random(); | |
return random.nextInt(max - min) + min; | |
} | |
private class CustomWebViewClient extends WebViewClient { | |
@Override | |
public boolean shouldOverrideUrlLoading(WebView view, String url) { | |
view.loadUrl(url); | |
return true; | |
} | |
@Override | |
public void onPageFinished(WebView view, String url) { | |
swipeRefreshLayout.setRefreshing(false); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment