What is the best way to perfectly center HTML text both vertically and horizontally within an Android TextView?

Take a look at my TextView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    
    <TextView
        android:id="@+id/tv"
        android:layout_width="300dp"
        android:layout_height="50dp"
        android:gravity="center"
        android:background="@android:color/darker_gray"
        android:text="5666" />
</LinearLayout>

here is some html text:

private static final String HTML_CONETNT = "<p>text example with centered alignment</p>\n";

and this is how I insert the html content into the textview:

mTv.setText(Html.fromHtml(HTML_CONETNT));

However, it's only centered horizontally. How can I get it to be vertically centered as well?

I attempted using css style:

    private static final String HTML_CONETNT = "<p style=\"text-align: center\">text example with centered alignment</p>\n";

but unfortunately, it didn't work as intended.

Answer №1

Everything seems to be functioning properly.

android:gravity="center_horizontal | center_vertical"

Answer №2

There is a helpful approach you can take to trim strings using the method provided in the following link.


String text = "<p>When seeking greatness, this place offers</p><p><strong>magnificence </strong>and <em>delightfulness. </em>Exceptionally<em> </em><u>pleasant</u></p>"

CharSequence trimmedText = trim(Html.fromHtml(text));
displayText.setText(trimmedText);

public static CharSequence trim(CharSequence string) {
        int start = 0;
        int end = string.length();
        while (start < end && Character.isWhitespace(string.charAt(start))) {
            start++;
        }

        while (end > start && Character.isWhitespace(string.charAt(end - 1))) {
            end--;
        }

        return string.subSequence(start, end);
    }

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

Categorize an array by their names using Jquery and present them as a list

I have a list of cities and their corresponding countries structured like the following: { "data": [ { "cityname": "Newyork", "countryname": "USA" }, { "cityname": "amsterdam", "countryname": "Netherland" },{ "cityname": "Washington", "country ...

Issue with displaying background image in mobile device despite successful display in browser and Chrome tools on Angular 18

Revamping my personal website (www.coltstreet.com) led me to explore media queries for displaying different background images. Testing on desktop and via Chrome tools showed positive results, but the real challenge arose when viewing the site on my actual ...

Conceal the galleryView plugin seamlessly without the need for a

I have implemented jQuery on my webpage to load content without refreshing, displaying only the necessary information. Within the gallery section, there are links for "Other Photography" and "Nude Art". Clicking on these links initializes the gallery with ...

I could use some help with understanding node.js scripts, running processes, and other related tasks

I'm currently trying to run a node.js script using CMD and I keep encountering an error. Here's the code snippet that's causing the issue: var mysql = require('mysql'); var log4js = require('log4js'); var io = requi ...

The username index is not defined in the file path C:xampphtdocsAppX1signin.php on line 6

Experiencing some challenges with a php script I recently created. As a beginner in php, I understand that my code may not be optimal. These error messages are displayed when the form is submitted: Notice: Undefined index: username in C:\xampp&bsol ...

Activate the JavaScript loader while data is being fetched

I'm currently working on incorporating a loader into my website that should remain visible throughout the entire loading process. For example, if the load time is around 6.8 seconds (with 6.3 seconds of waiting and 0.4 seconds of downloading), I want ...

What is the reason behind the line-height adjustment only impacting the top portion of the font?

Currently, I am experimenting with the dot HTML character to create icons in different colors. However, I am encountering an issue with the line-height property. It appears that the line-height setting only affects the placement of the top part of the char ...

Sending multiple arguments from an HTML form to a PHP function

Hey, I'm facing a situation where I have an HTML form and I need to pass its value as a parameter to a PHP function. However, there's another value that I need to include which is not even present inside the HTML code. Take this for example: &l ...

Having trouble finding the element for an image of a body part using xpath

When using driver.findElement(By.xpath(".//*[@id='bodyPartContainer']/div[1]")).click(); to select a part of the human body image, I'm encountering the following exception in webdriver: org.openqa.selenium.NoSuchElementException: no such ...

Is it possible to create dynamic animations with SVG files?

I am currently in the process of coding my website, and I came up with an exciting idea to animate my navigation bar within an SVG container. With its naturally wavy design, I aim to achieve a sweeping wave effect similar to the intro animation on Discord. ...

When I incorporate JavaScript logic into my navigation, the Anchor Links fail to work properly

Currently facing an issue with my navigation bar where the category jump labels should change their bootstrap class when the corresponding heading is visible in the viewport. While everything works fine up to this point, adding the second event listener fo ...

What is the best way to merge two images into a single image and apply color modifications using Javascript?

I am currently working on a website project for a Youtuber, and one of the features I'm implementing is a character editor. The editor is almost complete, but now I want to enable users to save their customized character as an image. You can access t ...

Instructions on how to alphabetically sort a String array in Android devices

Despite numerous solutions available for this particular issue, I am still encountering an error. The situation involves a string array where data is inserted via a web service. Below you can find the code snippet: protected void onPostExecute(String resu ...

Cancel a designated Thread initiated by IntentService

I need to download multiple files from my server to my device and I'm facing a challenge. This is what I have tried so far: Within Activities: ... Intent intent = new Intent(this, DownloadService.class); intent.putExtra(DownloadService.URL, url); s ...

Having difficulty sending the specified "id" to the server for a JSON response using Android Volley

As I move from the main activity to a detail and then to a comments activity in my Android app using Volley, I encounter an issue with displaying comments. The process involves passing a product id through intents as users interact with a listview populate ...

Tips for establishing uniform width for all Bootstrap columns

Having more than 12 columns in a row causes the columns to stack vertically, but the top ones have varying sizes compared to the bottom ones. <div class="container-fluid"> <div class="row"> <div class="col-md"></div> < ...

Is the default date time formatting in Android thread-safe?

I am investigating whether using the following code is thread safe: DateFormat dateFormat =android.text.format.DateFormat.getDateFormat(getApplicationContext()); While I am aware that the object DateFormat is not thread safe, it is a common practice in ...

Looking to bookmark Java links or a similar task?

Apologies for the lackluster title, as I am not well-versed in programming language and struggle to articulate my specific request... Allow me to explain: I frequently need to visit a particular website to conduct research (details below). I attempted usi ...

Tips for choosing an item in a multi-select dropdown using Selenium WebDriver

Currently delving into Selenium WebDriver while utilizing Java.. I am curious about how to select values in a Multi-select box where the options are already pre-selected. If I want to choose two or more additional options, how can I go about it? The HTML ...

Tips for creating and verifying letters/symbols with canvas?

My goal is to create an application where a background image with a letter will be presented, and users can draw over it by tracing the indicators with strokes. The key challenge here is to validate the strokes, including their order and direction. I have ...