In my graduation project ...
Can I use css in android app ? if yes how ?
How I can add two layout for one activity ?
You case use CSS in an android application through a WebView. What I usually do is injecting some JavaScript code to add styles to my elements.
Basic example for resizing images:
webView.getSettings().setJavaScriptEnabled(true);
webView.loadDataWithBaseURL(...);
webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:"
+ "var styles = document.createElement('STYLE'); "
+ "styles.innerHTML = 'img {width: ' + 200 + '; height:' + 200 + ';}';"
+ "document.body.appendChild(styles);");
}
});
Related
I am using an android WebView and I want to load webpage on my android device but display only some parts of webpage, not the whole page.
Is this possible?
I think what you want to do is remove some content from your HTML page and then display it in the WebView. This is possible via javascript so just before you display the page add some javascript code that will remove the elements you don't want.
LIKE
final WebView mWebView = (WebView) findViewById(R.id.mWebViewId);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
mWebView.loadUrl("javascript:(function() { " +
"document.getElementById('tableid')[0].style.display='none'; " +
"})()");
}
});
mWebView.loadUrl(youUrl);
Just replace document.getElementsByTagName('tableid') with document.getElementsByTagName('theElementYouWantToRemove') for every element and you're set. Original solution can be found at Display a part of the webpage on the webview android
for those who still looking for a solution:
WebView webView = findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
mWebView.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('className1')[0].remove();
document.getElementsByClassName('className2')[0].remove();
document.getElementsByClassName('className3')[0].remove();" +
"})()");
}
});
webView.loadUrl(url);
In Kotlin in this way:
view.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
view.loadUrl(
"javascript:(function() { " +
"var head = document.getElementsByClassName('header')[0].style.display='true'; " +
"var head = document.getElementsByClassName('art-bnr')[0].style.display='none'; " +
"var head = document.getElementsByClassName('container-box')[0].style.display='none'; " +
"var head = document.getElementsByClassName('blog-sidebar')[0].style.display='none'; " +
"var head = document.getElementsByClassName('footer-container')[0].style.display='none'; " +
"})()"
) } }
view.loadUrl(url)
I'm developing an Android application in which I have used an HTML file for help contents. I have used a WebView to display the content and every thing is fine.
The problem is that user can change the theme and font size of the application. How can I propagate these properties to the content of WebView? Exactly how can I change the font size and text color in WebView? Is there a simple way to do that or I should create different HTMLfiles or CSSes? How to handle the size units (dp, sp, ...)?
I will appreciate your help with this situation.
loadUrl("javascript:(document.body.style.backgroundColor ='red');");
loadUrl("javascript:(document.body.style.fontSize ='20pt');");loadUrl("javascript:(document.body.style.color ='yellow');");
On your android application, use following code to load a web page with user chosen font size and color:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new InredisChromeClient(this));
myWebView.setWebViewClient(new InredisWebViewClient(this));
myWebView.clearCache(true);
myWebView.clearHistory();
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.loadUrl("http://demo.com/content.html?font-size=12&fontcolor=blue");
On the content.html page, enable JavaScript and use jQuery and its function as below:
function getCssValue(sCSS)
{
var sPageURL = window.location.search.substring(1);
var sValues = sPageURL.split('&');
for (var i = 0; i < sValues.length; i++)
{
var sPair = sValues[i].split('=');
if (sPair[0] == sCSS)
{
return sPair[1];
}
}
}
$(document).ready(function(){
// Set the Font Size from URL
$('html').css('font-size', getCssValue('font-size'));
});
It is best to do theme activities using CSS and Javascript. However if we want to pass on some settings from Android to the WebView dynamically, it is possible and a solution is to use the JavascriptInterface. Here is one way of doing it:
Firstly, we define a class which will be used as a bridge between the Android app and the WebView for JS interactions.
Here WebInterface is an inner class in the Activity and hence it has direct access to myWebView, which is a WebView instance variable.
public class WebInterface {
private Activity activity;
public WebInterface(Activity activiy) {
this.activity = activiy;
}
#JavascriptInterface
public void changeTheme() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// All of the theme settings could go here, the settings passed on by Android
myWebView.loadUrl("javascript:document.body.style.backgroundColor ='red';");
myWebView.loadUrl("javascript:document.body.style.fontSize ='20pt'");
myWebView.loadUrl("javascript:document.body.style.color ='yellow';");
//OR load your data as shown here http://stackoverflow.com/a/7736654/891092
htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"theme.css\" />" + htmlData;
// lets assume we have /assets/theme.css file
myWebView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);
}
});
}
}
Note that it is very important to run your code in UI Thread otherwise it will not work.
Here is how the Activity registers the WebView with the JavascriptInterface:
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(jsInterface, "JSInterface");
In the HTML file, which the user is viewing, a button or widget could be made to change theme by calling code in Android through the bridge:
<input type="button" value="Say hello" onClick="doChangeTest()" />
<script type="text/javascript">
function doChangeTest(){
JSInterface.changeTheme(); // this calls the changeTheme in WebInterface
}
</script>
First you need to define a webView and after that use below method.
lightFont is your font that you should store in asset folder.
color is your text color.
font size : you can change font size.(for example 20px or medium and etc).
at the end you need to use seconde method to show html on webView
First Method:
public static String getStyledFont(String html) {
boolean addBodyStart = !html.toLowerCase().contains("<body>");
boolean addBodyEnd = !html.toLowerCase().contains("</body");
return "<style type=\"text/css\">" +
"#font-face {font-family: CustomFont;" +
"src: url(\"file:///android_asset/lightFont.ttf\")}" +
"body {color: #787878;}"+
"body {font-family: CustomFont;font-size: x-small;}</style>" +
(addBodyStart ? "<body>" : "") + html +(addBodyEnd ? "</body>" : "");
}
Second method:
String htmlText = getStyledFont(yourText);
webView.loadDataWithBaseURL("file:///android_asset/",
htmlText ,
"text/html; charset=UTF-8", null, null);
i need to display another website into my android webview without it's header and footer
wb.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
wb.loadUrl("javascript:(function() { " +"document.getElementsByTagName('header')[0].style.display=\"none\"; " + "})()");
}
});
wb.loadUrl(url);
setContentView(wb);
Why not use iframe?
Try something like this -
String iframe = "<iframe scrolling=\"no\" src=\"YOUR URL\"" +
"width=\"400px\" height=\"300\"></iframe>";
webview.getSettings().setJavaScriptEnabled(true); //be sure to enable this or
//page might not load properly
webview.loadDataWithBaseURL("", iframe, "text/html", "UTF-8", "");
//loading iframe
You can customize the iframe code according to your needs. Be sure to add \ before every " in your HTML Code.
I'm working on an Android project with webview. Everything works fine but I can't set text to a textarea. I have a bunch of pages that have a memo-writing option. I'm loading the code for the memo to a page with jQuery:
$('#memoContainer').load("memo.html");
memo.html textarea:
<div class="sisalto">
<textarea id="memo" style="width: 100%"> </textarea>
</div>
The textarea works, I can write in it and I can get the contents and save it in Android with jQuery:
function save(){
var newContent = $('#memo').val();
AndroidFunction.saveFile(newContent);
}
I'm trying to get the saved contents and set it in the textarea:
var setMemo = $('#memo');
setMemo.innerText("DOESNT WORK");
setMemo.val('NOPE');
I've tried googling and browsing here for hours but can't seem to find anything useful. Many suggest the .val('smth'); option but it just doesn't work.
The memo is loaded before trying to set the content and everything is OK in my opinion. What is the problem here and any idea on how can I get this done?
Okay, the problem was the load-function. It loads the memo.html and shows it on the page but the actual code isn't injected to the page. Hence I can't set text to the textarea because it isn't actually there.
You should use a 'complete' function callback
$('#memoContainer').load('memo.html', function() {
var setMemo = $('#memo');
setMemo.val('hello');
});
Are you enabling javascript with the WebView? You need this to enable javascript:
WebView webView = ...
webView.getSettings().setJavaScriptEnabled(true);
Be sure jQuery is correctly loaded, can you post your code?
Here a working example (need internet permission since it uses CDN to load jquery):
import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String html = "<html>\n" +
"<body>\n" +
"<textarea id=\"area\"></textarea>\n" +
"\n" +
"<script src=\"http://code.jquery.com/jquery-1.10.0.min.js\"></script>\n" +
"<script src=\"http://code.jquery.com/jquery-migrate-1.2.1.min.js\"></script>\n" +
"\n" +
"<script type=\"text/javascript\">\n" +
" $(document).ready(function() {\n" +
" var area = $('#area');\n" +
" area.val('Hello');\n" +
" });\n" +
"</script>\n" +
"\n" +
"</body>\n" +
"</html>";
String mime = "text/html";
String encoding = "utf-8";
setContentView(R.layout.activity_main);
WebView web = (WebView) this.findViewById(R.id.web);
web.getSettings().setJavaScriptEnabled(true);
web.loadDataWithBaseURL(null, html, mime, encoding, null);
}
}
I want to make an app which loads the content from the webpage into webview. I want to show only a particular thing in the entire webview, not the whole content of the webpage.
Here is an example. If I use: http://us.m.yahoo.com/w/search%3B_ylt=A2KL8xs0vUBQMg0AwAkp89w4?submit=oneSearch&.intl=us&.lang=en&.tsrc=yahoo&.sep=fp&p=digital+cameras&x=0&y=0 as the URL for the webview, it loads all the contents of the page on the webview. But I want to remove the banner of the page and show it on the webview of my application.
I have tried using adblocker using CSS tags, but that is not helping me. Please give me some idea for overcoming this problem.
Thanks.
Thank You for the answer Zyber. I have solved it using injection of JavaScript in the code for WebView in android.
final WebView webview = (WebView)findViewById(R.id.browser);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
webview.loadUrl("javascript:(function() { " +
"document.getElementsByTagName('header')[0].style.display="none"; " +
"})()");
}
});
webview.loadUrl("http://code.google.com/android");
This solved my purpose and it is easy to use to.
I got the solution to add this:
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
view.loadUrl("javascript:(function() { " +
"var head = document.getElementsByClassName('header')[0].style.display='none'; " +
"var head = document.getElementsByClassName('blog-sidebar')[0].style.display='none'; " +
"var head = document.getElementsByClassName('footer-container')[0].style.display='none'; " +
"})()");
}
});
view.loadUrl("your url");
Adding (var head =) looks like to hide my class in webview.
I hope this will be helpful for someone.
check Jsoup it provides an library which gives an easy way of extracting Html elements from a webpage
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toURI());
HttpResponse resp = client.execute(get);
String content = EntityUtils.toString(resp.getEntity());
Document doc = Jsoup.parse(content);
Elements ele = doc.select("div.classname");
This example executes an Http GET and then extracts an Div element with the class "classname" which you can then load in your webview