How to set text size in WebView in android

2019-01-16 20:55发布

I am using WebView to justify text. I want to know-

  1. Is it possible to set the text size in layout file? As I want different text size for different screen sizes.

  2. And also one problem is first background appears then after 2 second text display. Is it possible to display text immediately?

Size of text is 7-8 lines.

Code-

public class Main extends Activity {

       WebView mWebView;

       @Override
       public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);        
          mWebView = (WebView) findViewById(R.id.webview);
          String text = "<html><body>"+"<p align=\"justify\">"+getString(R.string.itext)+"</p>"+"</body></html>"; 
      mWebView .loadData(text, "text/html", "utf-8");
      mWebView .setBackgroundColor(Color.TRANSPARENT);
       }
}

Xml-

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:orientation="vertical" 
       android:layout_width="fill_parent"
       android:layout_height="fill_parent" 
       android:background="@drawable/light">

<WebView
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/transparent"/>
</LinearLayout>

7条回答
趁早两清
2楼-- · 2019-01-16 21:34

I'm not sure if this is what you're looking for, but as long as you don't want to set the text size based on a calculation with the text width/height, this should be what you're looking for:

WebSettings settings = yourWebView.getSettings();

This way you're getting the settings of the WebView whose text size you're trying to change.

There're some predefined values you can set as size using the TextSize class, for instance:

settings.setTextSize(TextSize.SMALLEST);
settings.setTextSize(TextSize.SMALLER);
settings.setTextSize(TextSize.NORMAL);
settings.setTextSize(TextSize.BIGGER);
settings.setTextSize(TextSize.BIGGEST);

You could simply choose which one you need to set depending on the parameters of the current device that you choose.

If you, on the contrary, want to make some kind of screen width/height calculation and set the result as a particular value, you may even use this:

settings.setDefaultFontSize(an_integer_that_goes_between_1_and_72);

---- EDIT ----

To enhace your WebView rendering, try the following:

mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

You could also try adding this to your Manifest file:

android:hardwareAccelerated="true"
查看更多
登录 后发表回答