Incorporate CSS and JavaScript styling into your Android application

I'm currently working on developing an Android app that will display a countdown for an upcoming event. I have utilized HTML, CSS, and JavaScript to create the functionality, which works perfectly fine when tested in a regular HTML environment. However, when integrated into Android Studio and displayed using WebView, the HTML page loads but without the associated CSS and JavaScript. Both the CSS and JavaScript files are located in the same directory as the HTML file. Below is a snippet of the code:

<html>
<head>
<link type="text/css" rel="stylesheet" href="flipclock.css" />


</head>
<body>

<div class="clock-builder-output"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="flipclock.js"></script>
<style text="text/css">body .flip-clock-wrapper ul li a div div.inn, body .flip-clock-small-wrapper ul li a div div.inn { color: #CCCCCC; background-color: #333333; } body .flip-clock-dot, body .flip-clock-small-wrapper .flip-clock-dot { background: #323434; } body .flip-clock-wrapper .flip-clock-meridium a, body .flip-clock-small-wrapper .flip-clock-meridium a { color: #323434; }</style>
<script type="text/javascript">
$(function(){
FlipClock.Lang.Custom = { days:'Days', hours:'Hours', minutes:'Minutes', seconds:'Seconds' };
var opts = {
clockFace: 'HourCounter',
countdown: true,
language: 'Custom'
};  
var countdown = 1495943700 - ((new Date().getTime())/1000); // from: 05/28/2017 09:55 am +0600
countdown = Math.max(1, countdown);
$('.clock-builder-output').FlipClock(countdown, opts);
});
</script>

</body>
</html>
Here's the implementation of the WebView within the MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String url = "file:///android_asset/www/index.html";
        WebView view = (WebView)this.findViewById(R.id.webView);
        view.getSettings().setJavaScriptEnabled(true);
        view.loadUrl(url);
        view.setWebViewClient(new MyBrowser());
    }
    private class MyBrowser extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading (WebView view,String url){
            view.loadUrl(url);
            return true;
        }
    }
}

Answer №1

It is necessary to have two separate folders for your "index" file. It is important to ensure that the external files do not interfere with the internal ones, so it is recommended to place the references to javascript and css within the internal folder. If this does not resolve the issue, consider moving the references to the external folder.

Best regards.

Answer №2

To include external CSS and JavaScript files, the URL construction used is similar to that of loading the HTML URL into a webview. For example, if you loaded the HTML file using:

    String url = "file:///android_asset/www/index.html";

then to load JavaScript from the same directory /asset/www/, you would use the following in the HTML:

    <script type="text/javascript" src="file:///android_asset/www/flipclock.js"/>

A stylesheet file can be loaded as follows:

    <link rel="stylesheet" type="text/css" href="file:///android_asset/www/myCss.css"/>

Additionally, to execute injected JavaScript dynamically on devices running pre-KIT-KAT, use:

    webView.loadUrl("javascript:(function(){####JSGOESHERE####})();");

and for post-KIT-KAT devices, use the following method:

    webView.evaluateJavascript("####JSGOESHERE####", null);

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

Strange conduct experienced when utilizing the Bootstrap toggle feature

As I navigate through using jQuery steps and bootstrap toggle, I've noticed a peculiar behavior that I can't quite explain. It seems like there might be some connection between the two, as when jQuery plugins or extensions are utilized within jQu ...

Dispatch is functioning properly, however the state remains unchanged

I'm currently developing an application that utilizes redux for state management. In a particular scenario, I need to update the state. Here is how my initial state and reducer function are set up: import { createSlice } from '@reduxjs/toolkit&a ...

Dynamic Text Labels in Treemap Visualizations with Echarts

Is it possible to adjust the text size dynamically based on the size of a box in a treemap label? I haven't been able to find a way to do this in the documentation without hardcoding it. Click here for more information label: { fontSize: 16 ...

Combine collapse and popover in Bootstrap 3 for enhanced functionality

I'm facing some issues trying to use the badge separately from the collapse feature. $(function (e) { $('[data-toggle="popover"]').popover({html: true}) }) $('.badge').click($(function (e) { e.stopPropagation(); }) ) Check o ...

Having difficulty interpreting the date

Currently, I am attempting to extract the date from the given format: dateFormat: "d-M-y" // results in 10-Oct-13 To format the date, I am utilizing jQuery UI. Here is the code snippet I am using: var d1 = new Date("10-Oct-13"); alert(d1); //Works cor ...

Prevent overlapping of nodes and edges in a D3 force-directed layout

Check out this fascinating example at http://bl.ocks.org/mbostock/1747543: In the demonstration, Mike illustrates how to prevent nodes from colliding with each other in a graph. I'm curious if it's feasible to also prevent collisions between no ...

Performing an Ajax POST request in plain JavaScript without utilizing the jQuery

I am looking to retrieve a JSON object from the server side via an URL that needs to be created on the client side (using JavaScript) using an ajax POST request. var oReq = new XMLHttpRequest(); oReq.open("POST", url, true); oReq.responseType = "json"; oR ...

Highlighting the current menu item by comparing the URL and ID

Looking to make my navigation menu items active based on URL and ID, rather than href. None of the suggested solutions (like this one, this one, or this one) have worked for me. This is how my Navigation is designed: <nav id="PageNavigation"& ...

Using JQuery, you can toggle a newly created DIV element by linking it to `$(this)` instead of `$(this).closest()`

In the comment section, there is a link called "Reply" that triggers a pop-up comment box when clicked. However, I want the comment box to disappear if the "reply" button is clicked again, as it currently keeps opening more comment boxes. $('.replyli ...

MongooseError: The parameter `uri` passed to the `openUri()` function must be of type string, but instead received "undefined"

Recently delving into mongo, I encountered a connection error that has me stumped. The error message reads as follows: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose ...

What is the best way to check the validity of an if statement within JavaScript or AngularJS?

Here is a snippet of code that I have: $scope.changePassword = function () { sessionService.save($scope.sessionData); if(sessionService.account.newPassword == sessionService.account.currentPassword) { ...

Encourage users to activate the physical web feature in compatible web browsers

Is it possible to use JavaScript to encourage users to activate the physical web (and thus BlueTooth), similar to how APIs like "getUserMedia()" prompt users? UPDATE: Given that this technology is still in its early stages and not extensively supported, t ...

Mistake in the hovering positioning within the WordPress theme

I've encountered a hover issue on my website that I'm trying to resolve. Every time I hover over a product, the product description appears underneath it instead of on top, and I can't seem to find a solution: The site is using the sentient ...

Is anyone else seeing a mysterious gray outline surrounding the image?

When visiting my website, I encountered an issue with the main menu. Specifically, when hovering over 'Populaire boeken', the first 2 menu items display properly with an image on mouseover. However, there seems to be a pesky grey border surroundi ...

Jquery date manipulation producing unexpected outcomes

I have encountered a common issue with my code. While the solutions I found online seem to work, the results are not as expected. My objective is to add a certain number of days (15, 30, 60) to a given date. However, the resulting dates have months changi ...

Removing data using axios in a React project

I'm currently working on a small app using the Json server package to help me keep track of movies I want to watch in my free time. I am looking to learn React and Axios, so I decided to build this app with these technologies. The concept is simple - ...

Is there a way to extract SVG data from the Echarts library in AngularJS?

Currently, I am attempting to retrieve the SVG of Echarts elements in angularjs. Despite my efforts to search for a solution, I have not come across anything useful yet. I require a similar function like the one I utilized with highchart: const chart ...

Centering an image on a webpage using CSS

Here is the code I am using for displaying my image: return <div class="imgContainer"><img src={broomAndText} alt="broomAndText" /></div> In my css file, I have included the following styling: .imgContainer { tex ...

Extracting information from a division using Selenium

I am attempting to choose an element for clicking on a page (). The element in question is a date selection within a calendar pop-up. Specifically, the element is: <div class="day unit in-range" data-time="1698822000000">1</d ...

challenges arise when using star icons to rate items visually, as the corresponding hidden values for backend processing are linked to radio input types

Hello, I am trying to retrieve the value of an input type radio by clicking on a star image visually. I have been successful in this, but I am having trouble resetting the star image in another row. You can view a demo of this here. I will explain what I ...