Android: WebView load image in center - android

I want to load an image at the web view, but it shows all at top_left of the web view. My picture is on the internet not local.
gifView.loadUrl(mImageUrl);
gifView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
view.getSettings().setLoadsImagesAutomatically(true);
if (mProgressBar != null) {
mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (mProgressBar != null) {
mProgressBar.setVisibility(View.VISIBLE);
}
}
});
Here is my xml:::
<WebView
android:id="#+id/gif_image"
android:background="#null"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Edit:i used:
String HTML_FORMAT = "<html><body style=\"text-align: center; background-color: null; vertical-align: middle;\"><img src = \"%s\" /></body></html>";
final String html = String.format(HTML_FORMAT, mImageUrl);
gifView.loadDataWithBaseURL("", html, "text/html", "UTF-8", "");
but my image only Horizontal Center,how to center

Try this.
myWebView.loadData("<html><head><style type='text/css'>body{margin:auto auto;text-align:center;} img{width:100%25;} </style></head><body><img src='www.mysite.com/myimg.jpeg'/></body></html>" ,"text/html", "UTF-8");

I did it by using some code and xml :
<WebView android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="251dp"
android:layout_below="#+id/download"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
and this (for horizental center) :
WebView loading = (WebView)rootView.findViewById(R.id.webview);
loading.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
loading.loadDataWithBaseURL("file:///android_asset/", "<html><center><img src=\"done.png\"></html>", "text/html", "utf-8", "");
Or this for (horizontal & vertical center) :
WebView loading = (WebView)rootView.findViewById(R.id.webview);
loading.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
loading.loadDataWithBaseURL("file:///android_asset/", "<html>\n" +
"<body bgcolor=\"white\">\n" +
" <table width=\"100%\" height=\"100%\">\n" +
" <tr>\n" +
" <td align=\"center\" valign=\"center\">\n" +
" <img src=\"loading.gif\">\n" +
" </td>\n" +
" </tr>\n" +
" </table>\n" +
"</body>", "text/html", "utf-8", "");

Try something like this:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
String data = "<body><center><img width=\"" + width + "\" src=\"" + url
+ "\" /></center></body></html>";
webview.loadData(data, "text/html", null);

Try this, this will make the content fit to your webview
WebView web = (WebView) findViewById(R.id.gif_image);
web.getSettings().setDefaultZoom(ZoomDensity.FAR);

Do you use Linear layout? So you will require to use the gravity property of the parent linear layout.
A good explanation of gravity in android: http://sandipchitale.blogspot.com/2010/05/linearlayout-gravity-and-layoutgravity.html

The reason is not in the webview, it is the html code.
W3c wants that "text-align" should no longer take effekt on block elements like images.
You can read more at center-image-using-text-align-center
So either you make your image display:inline or you center it in a different way e.g.
.center {
left: 50%;
margin-left: -50%;
}

Related

WebView with fixed Height

I have a container Webview which plays videos.I have fixed the size of container inside xml file by 200dp. Webview loads data by loading html format. Video is playing smoothly but problem is video height doesn't fit to the given size and user can drag video vertically up and down.Videos width is adjusting according to device size.But the problem is with adjusting video height.
xml code for container
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp">
<WebView
android:id="#+id/myWeb"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alwaysDrawnWithCache="true"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="#+id/progressBar3"
/>
</RelativeLayout>
xml code to init webview and load data
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setSaveFormData(false);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.clearFormData();
webView.clearCache(true);
webView.clearHistory();
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
view.clearHistory();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
view.clearFormData();
view.clearHistory();
view.clearCache(true);
super.onPageStarted(view, url, favicon);
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
}
});
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
String htmlData=getHtmlData(model.getVideo_url());
webView.loadData(htmlData, "text/html", null);
xml code to load Html data
private String getHtmlData(String imageUrl) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(
"<!DOCTYPE html>\n" +
"<html>" +
"<meta charset=\"UTF-8\">\n" +
"<meta name='viewport' content='width=device-width, initial-scale=1'>" +
"<head>" +
" <title title='Index'></title>" +
"</head>" +
"<body bgcolor='#000'>");
stringBuilder.append(
"<script>\n" +
"function dismissProgress() {\n" +
"Android.dismissProgress(0);" +
"}\n" +
"</script>\n");
stringBuilder.append("<img id='imgsrc' onload='dismissProgress();' src=" + imageUrl + " alt='No Video Found' class='w3-image' class='w3-image' style='width:100%; height:300' align='center' height=300 />");
stringBuilder.append("</body>" +
"</html>");
return stringBuilder.toString();
}
Sp what i am looking for is how to fit the video content inside given height, so that user wont be able to drag the video vertically?.It should adjust the video within the view's height.
You've given style='width:100%; height:300' in your html code. Try replacing it with height:100% or try reducing the height to 200px. :)

How can I load video into an app from backend?

My problem is how to a show video from the admin backend into my android app. When I and adding the iframe from TinyMCE Editor, it looks like this:
But in my android app I get this:
I cannot understand what exactly is happening and I'm sharing you a section of my code of what I'm doing in the fragment.
if (item.getContent().length() != 0) {
mWebView.setVisibility(View.VISIBLE);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setMinimumFontSize(14);
String htmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ "<head>"
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>"
+ "<style type=\"text/css\">body{color: #525252;} img {max-width: 100%; height: auto}</style>"
+ "</head>"
+ item.getContent()
+ "";
mWebView.loadData(htmlContent, "text/html; charset=utf-8", "UTF-8");
} else {
mWebView.setVisibility(View.GONE);
}
if (item.getImgUrl().length() > 0) {
imageLoader.get(item.getImgUrl(), ImageLoader.getImageListener(mItemImg, R.drawable.img_loading, R.drawable.img_loading));
mItemImg.setVisibility(View.VISIBLE);
mItemImgSeparatorLine.setVisibility(View.VISIBLE);
} else {
mItemImg.setVisibility(View.GONE);
mItemImgSeparatorLine.setVisibility(View.GONE);
}
mPostTopSeparatorLine.setVisibility(View.GONE);
mPostMessage.setVisibility(View.GONE);
if (item.getAllowComments() == 0 && App.getInstance().getId() != 0) {
mPostTopSeparatorLine.setVisibility(View.VISIBLE);
mPostMessage.setVisibility(View.VISIBLE);
mPostMessage.setText(getString(R.string.msg_comments_disabled));
}
if (App.getInstance().getId() == 0) {
mPostTopSeparatorLine.setVisibility(View.VISIBLE);
mPostMessage.setVisibility(View.VISIBLE);
mPostMessage.setText(getString(R.string.msg_auth_prompt_comment));
}
}
For my Android App I'm working with a WebView as you can see in the above code. Do you have any idea why is it not working as expected? Thanks for your help.
You are trying to load an iFrame in WebView. To do so, use first create a string with the HTML.
String html = "<iframe width=\"560\" height=\"315\" src=\"your_src\" frameborder=\"0\" allowfullscreen></iframe>";
Now call loadData.
mWebview.loadData(html, "text/html", null);

How can I properly justify text on a WebView on Android?

I wanted to justify the text of a TextView but I could not find any way to do that on the TextView so I have created a WebView.
The code to set the text on my WebView is the following:
WebView webview = (WebView) view.findViewById(R.id.webview);
webview.loadData(getString(R.string.webview), "text/html; charset=utf-8", "utf-8");
webview.setBackgroundColor(Color.TRANSPARENT);
And it works well, the text is being show justified (because I have created a body tag with style="text-align:justify;).
The problem is that, as I have loaded the text into the WebView, it spends some seconds to charge the text. Therefore, the rest of the layout is being shown before the text have appeared, making a strange visual effect.
I have tried to wait until the WebView is fully loaded (How to listen for a WebView finishing loading a URL?) but the text is never shown. Here is the code that I have by the moment:
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
webview.loadData(getString(R.string.webview), "text/html; charset=utf-8", "utf-8");
webview.setBackgroundColor(Color.TRANSPARENT);
}
});
So, how can I show a justify text at the same time as the rest of the layout?
Thanks in advance!
this is the picture:
this is the code that I used in my project
it doesnt take so much to load
void initVebView(WebView wvContent_Detail, String body) {
String HTML1 = "<html><head><style type=\"text/css\">#font-face {font-family: MyFont;src: url(\"file:///android_asset/%s\")}body {font-family: MyFont;font-size: medium;text-align: justify; line-height: %spx;}</style></head><body dir='rtl'>";
String HTML2 = "</body></html>";
String HTML3 = "<span style=\"font-weight:bold\">%s<br/><br/>%s</span>";
String HTML4 = "<style>img{display: inline;height: auto;max-width: 100%;</style>";
String str = String.format(HTML1, "IRANSansMobile_UltraLight.ttf", 25);
String content = body.replace("text-align:", "");
content = content.replace("font-family:", "");
content = content.replace("line-height:", "");
content = content.replace("dir=", "");
content = content.replace("width=", "width=\"100%;\"");
String myHtmlString = str + content + HTML2;
wvContent_Detail.loadDataWithBaseURL(null, HTML4 + myHtmlString, "text/html", "UTF-8", null);
WebSettings webSettings = wvContent_Detail.getSettings();
webSettings.setDefaultFontSize(20);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
}
this is the xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context="ir.tenthwindow.BaseModule.ui.FragmentVideo">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webview_product_details"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" />
</ScrollView>
</FrameLayout>
you can use your font instead.
Hope this helped .

Android WebView link color

I am using WebView to show websites inside my application, and I was wondering is it possible to change link color and style which is by default blue and underlined?
I searched about it but there are all questions and solutions about removing the highlight around the link, nothing about the link itself. I just want to know is there some solution as easy as TextView's android:textColorLink or will I need to alter the website body somehow?
Thanks!
Okay, I managed to do it and wanted to share my way for the future visitors.
First I created a css file with the desired style, named style.css, saved under assets folder
a {color:purple; text-decoration:none}
Then, in the code I loaded the page as follows where content is the actual html content of the page
String htmlBody = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />" + content;
mWebView.loadDataWithBaseURL("file:///android_asset/", htmlBody, "text/html", "utf-8",
null);
That's it! Hope it helps somebody.
Here is an example of how to add html links and customize them:
WebSettings webViewSettings = webView.getSettings();
webViewSettings.setDefaultFontSize(AppSettings.defaultFontSize);
webView.setBackgroundColor(Color.TRANSPARENT);
webView.loadDataWithBaseURL("file:///android_asset", Util.replaceLinkTags(myText), "text/html", "utf-8", null);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("file")) {
Intent intent = new Intent(MyActivity.this, MyActivity.class);
intent.putExtra("word", Uri.parse(url).getLastPathSegment());
startActivity(intent);
return true;
} else
return false;
}
});
public static String replaceLinkTags(String text) {
text = "<html><head>"
+ "<style type=\"text/css\">body{color:" + "#424242" + ";} a{color:#00B8D4; text-decoration:none; font-weight:bold;}"
+ "</style></head>"
+ "<body>" + text + "</body></html>";
String str;
while ((text.indexOf("\u0082") > 0)) {
if ((text.indexOf("\u0082") > 0) && (text.indexOf("\u0083") > 0)) {
str = text.substring(text.indexOf("\u0082") + 1, text.indexOf("\u0083"));
text = text.replaceAll("\u0082" + str + "\u0083", "" + str + "");
}
}
return text;
}

you tube video not displaying on webview?

I'm trying to show youtube video on webview from url . After a long hour its working but still not shown anything :-
image
as you seen above image not shown any thing but seek bar of video increasing (but not shown anything and i m using API 17 and 480*800(WVGA)) and below is my code:-
Code
movie_image_movie_link.setOnClickListener(new OnClickListener() {
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(act);
// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.show_video_from_youtube);
dialog.setTitle("YouTube Video");
WebView video = (WebView) dialog.findViewById(R.id.webview);
video.getSettings().setJavaScriptEnabled(true);
video.getSettings().setPluginState(WebSettings.PluginState.ON);
// video.getSettings().setUserAgent(0);
video.setWebChromeClient(new WebChromeClient() {
});
String id = StringUtils.substringBetween(
MovieJSONObjectHandle.youtube_link,
"www.youtube.com/watch?v=", "&amp");
System.out.println("url => "
+ Uri.parse("http://www.youtube.com/v/" + id)
.toString());
final String mimeType = "text/html";
final String encoding = "UTF-8";
String html = getHTML(id);
video.loadDataWithBaseURL("", html, mimeType,
encoding, "");
dialog.show();
}
});
public static String getHTML(String videoId) {
String html = "<iframe class=\"youtube-player\" "
+ "style=\"border: 0; width: 100%; height: 90%;"
+ "padding:0px; margin:0namepx\" "
+ "id=\"ytplayer\" type=\"text/html\" "
+ "src=\"http://www.youtube.com/embed/" + videoId
+ "?fs=0\" frameborder=\"0\" " + "allowfullscreen autobuffer "
+ "controls onclick=\"this.play()\">\n" + "</iframe>\n";
/**
* <iframe id="ytplayer" type="text/html" width="640" height="360"
* src="https://www.youtube.com/embed/WM5HccvYYQg" frameborder="0"
* allowfullscreen>
**/
return html;
}
also try video instead of iframe but still same problem :-
String html = "<video id=\"video\" width=\"320\" height=\"240\" src=\"http://www.youtube.com/embed/" + videoId
+ "autobuffer controls onclick=\"this.play();\">";
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="400dp"
android:layout_height="400dp"
android:gravity="center"
android:orientation="vertical" >
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="match_parent" />
</LinearLayout>
mainfest
<activity
android:name="biz.xicom.defindme.controlpage.ControlPage"
android:hardwareAccelerated="true"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Light.NoTitleBar" >
</activity>
so if u had face this problem in past so please tell me what mistake i have done in above code.
Try this:
webView = (WebView) findViewById(R.id.webView);
mWebViewClient = new myWebViewClient();
webView.setWebViewClient(mWebViewClient);
mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSaveFormData(true);
webView.loadUrl("http://m.youtube.com"); // your web url

Categories

Resources