I found that this question has been asked before How to resolve overlapping the content of the webview here, but it was closed for some reason. But here is what happens. I have created a webview, applied transparent background, but when i try to load something, and reload something again, the older content will still remain on the webview and the newer one will overlap it. Here is a picture that explains it.
So i am creating a jokes application, and i have added webview. Then i added transparency and the random joke button reloads the webpage so that the webview can get another joke. But it just overlapps instead. Any solutions? Here is my piece of code
Button random = (Button) findViewById(R.id.reload);
final WebView web = (WebView) findViewById(R.id.webView);
web.setBackgroundColor(Color.TRANSPARENT);
web.setWebViewClient(new WebViewClient());
String selected = (String) getIntent().getCharSequenceExtra("selected");
final String url = "http://someurl.com/?s=dirty&x=" + selected;
web.loadUrl(url);
random.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
web.loadUrl(url);
}
});
Any help would be really appreciated :)
Try before doing web.loadUrl(url); doing web.clearView();
See docs.
Related
I want to make an app where the user can get random youtube videos in a webview by clicking a button.
I already can show a video in my webview with the url but I want to get any random video from youtube by clicking my button.
In my xml file I have a webview and a button
´´´
MainActivity.java
´´´
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path = "https://www.youtube.com/watch?v=1uwvxTT5V5M";
String dataUrl =
"<html><body>Video From YouTube<br><iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/embed/47yJ2XCRLZs\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
WebView showYoutubeVideo = (WebView) findViewById(R.id.zufallvideo);
showYoutubeVideo.setWebViewClient(new WebViewClient(){
public boolean shouldoverloadUrlLoading(WebView view, String url) {
return false;
}
});
showYoutubeVideo.getSettings().setJavaScriptEnabled(true);
showYoutubeVideo.loadData(dataUrl,"text/html", "utf-8");
}
}
TL;DR: it's complicated.
Until Youtube exposes an endpoint in their API to do this, you're gonna need to find a workaround.
Some would suggest to query a search with "IMG" followed by a random integer (ex. "IMG 22930"). The end result is quite surprising, since tons of videos are uploaded without renaming.
Here's an example of this workaround implementation in python: https://github.com/0x01h/random-youtube-video-generator
how can i open the html string that has a href on webview only instead of going on your browser?
i am using the LinkMovementMethod, this is okay on opening it on other app like video from youtube but i have some links that needs to be open only on webview.
here is a sample html string
String html_text = "<h1>sample text</h1><p><small>February 1 1970</small></p><p class=\"text-center\"><img src=\"https://www.google.com\" /></p><p>sample (here).</p>"
i need the a href to be open only on webview.
here is my code
DetailActivity
public class DetailActivity extends AppCompatActivity implements Html.ImageGetter {
private TextView newsContentTv;
private WebView newsWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_news);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
newsWebView = (WebView) findViewById(R.id.newsWebView);
setSupportActionBar(toolbar);
// add back arrow to toolbar
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
newsContentTv = (TextView) findViewById(R.id.textNewsContext);
Intent i = getIntent();
String news_content = i.getStringExtra("detail_content");
Spanned spanned = Html.fromHtml(news_content, this, null);
Spannable spannable = new SpannableString( Html.fromHtml(news_content) );
newsContentTv.setText(spanned);
newsContentTv.setMovementMethod(LinkMovementMethod.getInstance());
}
any help would be really appreciated.
// Create an unencoded HTML string
// then convert the unencoded HTML string into bytes, encode
// it with Base64, and load the data.
String html_text =
"<h1>sample text</h1><p><small>February 1 1970</small></p><p class=\"text-center\"><img src=\"https://www.google.com\" /></p><p>sample (here).</p>";
String encodedHtml = Base64.encodeToString(html_text.getBytes(),
Base64.NO_PADDING);
newsWebView.loadData(encodedHtml, "text/html", "base64");
I hope this will help you.
WebView webview = (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadDataWithBaseURL("", data, "text/html", "UTF-8", "");
Your question states you need to open the clicked url in your webview instead of navigating to browser. I can think of two ways to do this.
First case, if its not necessary to have a Textview to display the clickable link then you can load your string into the WebView itself (as others mentioned) and set a WebViewClient (this part is important)
newsWebView.loadDataWithBaseURL(null, html_text, "text/html", "UTF-8", null);
newsWebView.setWebViewClient(new WebViewClient());
// add below line to support youtube videos etc.
newsWebView.getSettings().setJavaScriptEnabled(true);
newsWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
so that any click keeps the navigation in the same WebView. Without the client it will navigate to the browser. But you should note this will load and replace the content inside, so your original link will not be there on screen.
Second case, if you need the clicks to be from the TextView simply setting newsContentTv.setMovementMethod(LinkMovementMethod.getInstance()); won't work as by default it will make the normal intent causing it to navigate to browser or related apps, you need to remove that. Then, you have to create a custom class extending LinkMovementMethod and override the touch event to load the url clicked into your webview as shown below:
public class CustomLinkMovementMethod extends LinkMovementMethod {
private static CustomLinkMovementMethod instance;
public static CustomLinkMovementMethod getInstance() {
if (instance == null)
instance = new CustomLinkMovementMethod();
return instance;
}
#Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP) {
int x = (int) event.getX() - widget.getTotalPaddingLeft() + widget.getScrollX();
int y = (int) event.getY() - widget.getTotalPaddingTop() + widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] urlSpans = buffer.getSpans(off, off, URLSpan.class);
if (urlSpans.length != 0) {
// You can check log to see if you are getting the url on click.
Log.d("TAG", String.valueOf(urlSpans[0].getURL()));
/* If you've made this an inner class in your activity
you can directly load the url into your webview.
Else you will have to create listeners to get url in activity
on event trigger */
newsWebView.loadData(urlSpans[0].getURL());
return true;
}
}
return super.onTouchEvent(widget, buffer, event);
}
}
use this on the TextView like
newsContentTv.setMovementMethod(CustomLinkMovementMethod.getInstance());
See if this works for you, hadn't expected the answer to become this long.
I'm building android app where, I placed links to the page in webview on which multiple links are there pointing to PDFs. Everyday, new links are updated. I want to make such functionality that when user clicks on the particular PDF link, it should get opened in default PDF viewer or there itself.
Right now, nothing is happening when user clicks on PDF link within webview.
WebView w=(WebView)findViewById(R.id.web1);
WebSettings webSettings=w.getSettings();
webSettings.setDomStorageEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
w.setWebViewClient(new WebViewClient());
w.loadUrl("http://collegecirculars.unipune.ac.in/sites/examdocs/_layouts/mobile/view.aspx?List=7ed6607e-6c43-401a-a922-bf8d8bf08ed8&View=dc261157-c533-4a60-977b-506fd87b2a19");
You can use Google Docs Viewer to read your pdf online:
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "http://collegecirculars.unipune.ac.in/sites/examdocs/Examiantions%20Timetables/Master-In-ARTS(M.A)(Rev.2008)-(24908)_Spl4-8-16.pdf?Mobile=1&Source=%2Fsites%2Fexamdocs%2F_layouts%2Fmobile%2Fview%2Easpx%3FList%3D7ed6607e%252D6c43%252D401a%252Da922%252Dbf8d8bf08ed8%26View%3Ddc261157%252Dc533%252D4a60%252D977b%252D506fd87b2a19%26ViewMode%3DSimple%26CurrentPage%3D1";
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
open in browser
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);
To override current URL :
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// here you can check PDF
url = url.toLowerCase();
view.loadUrl(url);
return true;
}
}
set this MyWebViewClient to your webView.
PaymentWebViewClient paymentWebViewClient = new PaymentWebViewClient();
webView.setWebViewClient(paymentWebViewClient);
I have a WebView that shows the content from a HTML file with a SVG object and inside it some clickable objects with a onclick() function calling the Android interface with java.performClick().
Here's a code sample:
WebView wvMapa = (WebView) findViewById(R.id.wvMapa);
wvMapa.getSettings().setBuiltInZoomControls(true);
wvMapa.getSettings().setSupportZoom(true);
wvMapa.loadUrl("file:///" + file.getAbsolutePath());
WebSettings wsMapa = wvMapa.getSettings();
wsMapa.setJavaScriptEnabled(true);
wvMapa.addJavascriptInterface(new Object(){
public void performClick(String id){
/*MY ACTION*/
}
}, "java");
It works great on the first run, but when I click Home button and after Resume or open another Intent and go back, it doesn't work anymore. Looks like the JavascriptInterface is unattached everytime I leave the screen.
What's missing?
In my game, I'd like to have a kind of "message of the day" feature. Basically, when the user taps the "message of the day" button in the main menu, it would open up a browser view in-game. When the user is done, he taps a "close" button and the view disappears, returning him to the game menu.
So, is it possible to create a browser view dynamically? If yes, how?
The following can be used in a Dialog as well
public void setWebView() {
//WebViewClient is used if you want to capture stuff from the webview, like if a link was pressed
WebViewClient yourWebClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
open_web = true;
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
Intent browserIntent = new Intent("android.intent.action.VIEW",
Uri.parse(url));
startActivity(browserIntent);
return true;
}
};
WebView wv = (WebView) findViewById(R.id.webview);
wv.setWebViewClient(yourWebClient);
String str = getHtml();
wv.loadData(str, "text/html", "utf-8");
wv.setBackgroundColor(0);
}
boolean isAsset = false;
private String getHtml(){
InputStream source = null;
if (isAsset){
source = getAssets().open("motd.html");
} else {
source = new FileInputStream(Environment.getExternalStorageDirectory() + "motd.html");
}
}
You could probably just use a WebView. When you want it to show up you could just set its view state to View.VISIBLE. When you want it to go away, just set its view state to View.GONE.
You can add/remove a WebView to your game dynamically (or show/hide it, whatever you prefer).
Take a look at the WebView tutorial for more info:
http://developer.android.com/resources/tutorials/views/hello-webview.html
Make sure to leave room for your "Close" button in your layout, i.e. you don't want to set the layout height to "fill_parent".