Creating a visually appealing layout by dividing HTML content into two columns within a WebView

Utilizing WebView in my application to display html content for reading ebooks presented a challenge during development. After parsing the ebook and converting it into an html string, I load this string into the WebView component.

  myView.setVerticalScrollBarEnabled(false);
  myView.setHorizontalScrollBarEnabled(false);
  myView.getSettings().setDisplayZoomControls(false);

  myView.getSettings().setJavaScriptEnabled(true);
  if (Build.VERSION.SDK_INT >= 11) myView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);

  myView.loadDataWithBaseURL("file:///android_asset/Text/", ebookContent, "text/html", "UTF-8", null);

To navigate horizontally through pages, I use 'myView.scrollTo(width of myView * countPages, 0)'. The formatting and styling of the content is achieved by implementing HTML formatting recommended by Uday Sravan K.

  myView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
    @Override
    public void onPageFinished(WebView view, String url) {
        // implementation details here...
       // more code here...
      });

The process involves splitting up the content within the WebView into chunks sized based on the width of the webview. While single-column display works well across various emulators and orientations, issues arise when dividing content into two columns due to discrepancies in widths between the page and the WebView.

For instance, on a device like Nexus 7 with specific dimensions, the calculated lengths may not align perfectly when displayed in two columns. This discrepancy can lead to artifacts and visible edges of neighboring pages creeping into the viewing region.

Efforts to dynamically adjust the content size or zoom level to rectify this issue have proven challenging as they affect the overall layout and readability of the content.

Seeking advice on better strategies to handle two-column display within WebView while maintaining precise positioning and preventing visual artifacts.

Answer №1

The specifications of Css state that elements' dimensions can be expressed in fractional numbers, but it appears that webkit only accepts integers.
When WebView is scrolled at a specific distance outlined below, the pages appear neatly.

 if (areThereTwoColumns) {
     view.loadUrl("javascript:(function(){mySheet.insertRule('html{ " +
                 "height: " + heightPage / density_ + "px;" +
                 " -webkit-column-width: "+ (widthPage - gap) / 2 / density_ + "px; " +
                 "-webkit-column-gap: " + gap / density_ + "px;" +
                 " font-size: " + textSize + ";}', ruleIndex)})()");
    // scrolling distance:
    scrollDistance = 2 * ((int)((widthPage - gap) / 2 / density_)  * density_  +
                        (int)(gap / density_) * density_ );

 } else { ......  }


 // myView.scrollTo((int)(scrollDistance * countPages), 0) etc

I'm uncertain whether this solution is ideal, but it suits my needs for now. I would really appreciate any suggestions for improvement.


This method works effectively for SDK 16 (tvdpi):

 areThereTwoColumns = areThereTwoColumns && getApplicationContext()
       .getResources().getConfiguration()
          .orientation == Configuration.ORIENTATION_LANDSCAPE; 
 // ............omitted
 if (Build.VERSION.SDK_INT == 16 && getResources().getDisplayMetrics()
                              .densityDpi == DisplayMetrics.DENSITY_TV)
   {
      scrollDistance = 2 * ((int)((widthPage - gap) / 2 / density_ +.5f)  * density_ +
                            (int)(gap / density_+.5f) * density_ );
   }
 // .............omitted

, In other scenarios, alternate methods must be employed as even with one column, the page display may become distorted (tvdpi !) for example :

int countGates = Math.round((float)myView.computeHorizontalScrollRange() / (widthPage + ((areThereTwoColumns)?gap:0)));
scrollDistance = (float) lengthMyView / countGates;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extracting the value of an attribute from an XML element and converting it into an HTML unordered list with

Here is an example of an xml file structure: <root> <child_1 entity_id = "1" value="Game" parent_id="0"> <child_2 entity_id="2" value="Activities" parent_id="1"> <child_3 entity_id="3" value="Physical1" parent_id="2"> ...

After uploading the WordPress theme, the wp_enqueue_style() function fails to work properly

I recently developed a new WordPress theme and encountered an issue while trying to load specific stylesheets for my child sites using the is_page(array('')) function in my function.php file. Surprisingly, only the files that were added to all of ...

Is there a way to alter a class using ng-class only when the form is deemed valid?

I am trying to implement a feature where an input field shows as required, but once the user enters text, it indicates that the input is valid by changing the border color from red to green. I am facing an issue with this line of code always returning fal ...

Is there a way to eliminate this from the footer section?

Check out my website: If the text is not visible, try using a larger monitor or zooming out in your browser. I've added an image to help explain: I only want to remove that element + title on the first page This is the HTML code: <div id="to ...

Avoiding redirection in Django template form

Currently, I am facing a challenge with my application that involves rendering a Django Template model form where images are referenced from another model. To manage the addition and deletion of images for this other model, I have implemented a button wit ...

Utilizing PHP and AJAX to Extract Information from a MySQL Database

My goal is to fetch data from a MySQL database hosted on a webserver and display it in an HTML table. I've been following an example on W3Schools, but I'm facing issues retrieving the data successfully. Here is the source code: (HTML) <html& ...

What is the best way to center align tabs in a Bootstrap 4 list?

I am working with tabs structured like this: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/> <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist"> <li class="nav-item"> ...

Accessing and manipulating web elements using either XPath or CSS selectors

Having trouble selecting a specific piece of information using xpath or css selector. Error messages keep appearing. Can someone help identify the issue? This snippet is from my code: output = driver.find_element_by_xpath("//td[@class_= 'sku']" ...

Efficiently loading Google Visualizations for core charts by utilizing AJAX within jQueryUI tabs

Loading Google Visualizations via AJAX in jQueryUI tabs After encountering a similar issue, I discovered a solution provided in the link above that partially resolved my problem. I am trying to use Google Visualization core charts within jQueryUI tabs wit ...

Embed Socket.IO into the head tag of the HTML document

After working with socket.IO and starting off with a chat example, my chat service has become quite complex. The foundation of my code is from the original tutorial where they included <script src="/socket.io/socket.io.js"></script> <scrip ...

Expanding an element to cover all columns in a grid with automatically generated columns

I am working on a CSS grid layout with automatic columns and 2 rows. All elements are normally placed in the first row except for one special element that should span both rows while filling all available column space. My current code looks like this: ...

Pause until the existence of document.body is confirmed

Recently, I developed a Chrome extension that runs before the page fully loads by setting the attribute "run_at": "document_start". One issue I encountered is that I need to insert a div tag into the body of the webpage as soon as it is created. However, a ...

What is the best approach to managing categorical variables with Flask?

After developing a machine learning model to classify a target variable Y based on predictors x1, x2, x3, and others, I needed to create an HTML form "calculator" for users. The form requires the user to input data for x1, x2, x3, etc., and then displays t ...

JavaScript has encountered a syntax error

When working on an animation in javascript, I encountered a problem that I can't seem to identify. I am attempting to make the pan function work with the "mover" function, but it seems like either I am not using the properties correctly within the "tr ...

Determining the Number of Sub-Menu Items Using jQuery without Reliance on CSS Classes

I've scoured the depths of Google and SO in search of answers, but nothing quite fits the bill. My mission is to create a submenu without using classes, adding a style attribute to each individual <li> within the sub <ul> that sets a min- ...

Utilizing various z-index values for multiple background images in a single CSS class

My approach may be completely off. I am in the process of building a website using sliced images from a .PSD file created by a graphic artist. Essentially, the background image consists of 4 green bars angled at 45 degrees slightly intertwined with 3 blue ...

Streamlining programming by utilizing localStorage

Is there a more efficient way to streamline this process without hard-coding the entire structure? While attempting to store user inputs into localStorage with a for loop in my JavaScript, I encountered an error message: CreateEvent.js:72 Uncaught TypeErr ...

Establishing updated file path for resources in JavaScript based on environment

I'm currently facing an issue with my external Javascript file that uses the getScript() function to execute another JS file. Both files are located on static.mydomain.com, as I am trying to set up a Content Delivery Network (CDN) for the first time. ...

Having trouble setting a background image for my CSS button

Recently started experimenting with button styles and I wanted to create a design where there is a background image on the left of the button with text located on the right side of the image. Here's the code snippet I've been working on. Here&apo ...

What is the best way to clear the content of a contenteditable element in React?

I have a scenario where I am rendering an array of items, each with a contenteditable field. MainComponent.js import { useState } from "react"; import Item from "./Item"; import "./styles.css"; export default function MainC ...