Ziem My personal blog

Html class - basic usage

From time to time, there is a need to display some styled text in an Android application. You can always use Spans to achieve your goals, but if you know HTML, you could consider using Html class.

The Html class with ImageGetter and TagHandler interfaces is used to convert HTML strings into styled text. At the time of writing Html class contains four static methods:

static String escapeHtml(CharSequence text);
static Spanned fromHtml(String source);
static Spanned fromHtml(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler);
static String toHtml(Spanned text);

The first method allows us to get an HTML-escaped representation of given plain text. The fourth we can use when we want to get an HTML representation of the provided Spanned text. fromHtml methods return styled text (Spanned) from provided HTML string. You may wonder, how does it work? As you can find at https://grepcode.com Html class parses HTML strings using TagSoup which is a SAX-compliant parser written in Java.

In this post, I will focus on the second method because, in my opinion, it is used most of the time. Let’s assume that we would like to display the following text:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras ut magna eget erat fermentum dignissim. Aenean interdum ultrices sapien1. Vestibulum feugiat ultrices neque, vel pretium massa. Etiam tempor luctus dui eget aliquam. In nec metus sit amet orci facilisis pretium.

Creating Spans manually can be cumbersome so let’s use a fromHtml method.

First of all, we have to create an HTML representation of our text:

<b>Lorem ipsum dolor</b> sit <u>amet</u>, consectetur <font color="green">adipiscing</font> elit. <i>Cras ut magna eget erat fermentum dignissim.</i> Aenean interdum ultrices sapien<sup>1</sup>. <font color="red">Vestibulum feugiat ultrices neque, vel pretium massa. Etiam tempor luctus dui eget aliquam.</font> In nec metus sit amet orci facilisis pretium.

next, we put it into a string.xml file:

<string name="lorem"><![CDATA[<b>Lorem ipsum dolor</b> sit <u>amet</u>, consectetur <font color="green">adipiscing</font> elit. <i>Cras ut magna eget erat fermentum dignissim.</i> Aenean interdum ultrices sapien<sup>1</sup>. <font color="red">Vestibulum feugiat ultrices neque, vel pretium massa. Etiam tempor luctus dui eget aliquam.</font> In nec metus sit amet orci facilisis pretium.]]></string>

in the *Activity.java file we use the Html class:

TextView textView = ...;
String string = getString(R.string.lorem);
Spanned spanned = Html.fromHtml(string);
textView.setText(spanned);

and voilà:

Screenshot of the result

If you would like to know what other methods return, I’m attaching snippets.

escapedHtml method returns:

&lt;b&gt;Lorem ipsum dolor&lt;/b&gt; sit &lt;u&gt;amet&lt;/u&gt;, consectetur &lt;font color=green&gt;adipiscing&lt;/font&gt; elit. &lt;i&gt;Cras ut magna eget erat fermentum dignissim.&lt;/i&gt; Aenean interdum ultrices sapien&lt;sup&gt;1&lt;/sup&gt;. &lt;font color=red&gt;Vestibulum feugiat ultrices neque, vel pretium massa. Etiam tempor luctus dui eget aliquam.&lt;/font&gt; In nec metus sit amet orci facilisis pretium.

and toHtml method returns:

<p dir="ltr"><b>Lorem ipsum dolor</b> sit <u>amet</u>, consectetur <font color ="#00ff00">adipiscing</font> elit. <i>Cras ut magna eget erat fermentum dignissim.</i> Aenean interdum ultrices sapien<sup>1</sup>. <font color ="#ff0000">Vestibulum feugiat ultrices neque, vel pretium massa. Etiam tempor luctus dui eget aliquam.</font> In nec metus sit amet orci facilisis pretium.</p>

Be aware that the Html class doesn’t support all HTML tags. Unfortunately, the documentation doesn’t say which are supported: Issue 8640: Documentation which tags are supported by Html.fromHtml(). Thanks to Mark Murphy, you can find a list of supported tags in Android 2.1 on his blog: HTML Tags Supported By TextView. Besides, using GrepCode you can always check it by yourself.

fromHtml method parses provided string so I advise not to invoke it on the UI thread when displaying longer text. Additionally, you should consider caching returned Spanned object (e.g. in lists).

In my next posts, I will explain how to use images and handle unsupported tags with the Html class.


Android N Developer Preview is here!

Today Google released Android N Developer Preview. If you would like to find more information, please visit developer.android.com.

There you will find six sections:

In the Program Overview section, you will find information about the timeline and updates of preview releases.

Android N for Developer describes changes in Android SDK which include:

multi-window-support

notification-replaynotification-groupnotification-group-expanded

Behavior Changes section tells you about:

  • Performance Improvements – Doze & Project Svelte
  • Permissions Changes – Android N introduces new permission: ACTION_OPEN_EXTERNAL_DIRECTORY also GET_ACCOUNTS is now deprecated
  • Accessibility Improvements – Screen Zoom enables a user to magnify or shrink all elements on the screen
  • Platform Migration toward OpenJDK 8, NDK Apps Linking to Platform Libraries, and Android for Work

Set Up the Preview guides you on how to get Android Studio 2.1, N Preview SDK, Java 8 JDK, and set up your development environment.

Thanks to Jack you can now use Java 8 features in Android back to Gingerbread. The following Java 8 features are available when targeting the Android N Preview:

You can enable Java 8 in Android Studio by setting the JDK Location field to the location of the Java 8 JDK and updating your build.gradle file:

android {
    compileSdkVersion 'android-N'
    buildToolsVersion 24.0.0

    ...

    defaultConfig {
        minSdkVersion 'N'
        targetSdkVersion 'N'

        ...
    }

    ...

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Be aware that the Instant Run does not currently work with Jack and will be disabled.

The Samples section contains 5 sample apps that demonstrate new Android N features including:

In the Support and Release Notes section will find notes, known issues, and general advisories.

If you would like to read more about the new developer preview release, please visit:


Google Maps - misc

Are you tired fighting (Support)MapFragment? There is a simpler solution: use MapView.

MapView class can be used instead of [Support]MapFragment. It’s a view which extends FrameLayout and displays a map.

If you want to use it you just need to forward these lifecycle methods

  • onCreate(Bundle),
  • onResume(),
  • onPause(),
  • onDestroy(),
  • onSaveInstanceState(),
  • onLowMemory(),

and voilà.

It has the same callbacks as map fragment:

  • getMap() that is deprecated and should be used in favour of asynchronous one,
  • getMapAsync() that is triggered when the map is ready to be used.

There is also a lite mode map:

The Google Maps Android API can serve a static image as a ‘lite mode’ map.

A lite mode map is a bitmap image of a map at a specified location and zoom level. Lite mode supports all of the map types (normal, hybrid, satellite, terrain) and a subset of the functionality supplied by the full API. Lite mode is useful when you want to provide a number of maps in a stream, or a map that is too small to support meaningful interaction.

You can enable it programmatically:

GoogleMapOptions options = new GoogleMapOptions().liteMode(true);

or in your layout/*.xml file:

<fragment xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:map="https://schemas.android.com/apk/res-auto"
    android:name="com.google.android.gms.maps.MapFragment"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    map:cameraZoom="13"
    map:mapType="normal"
    map:liteMode="true" />

In the documentation, you can find all the things it supports.

Snapshot

Yet another feature Google Maps offer are snapshots:

You can use the Google Maps built-in snapshot method, to capture a preview and display it in an ImageView.

To learn more, I recommend reading: Android Google Map to show as a picture.

Utils

There is also a project called Google Maps Android API utility library which provides extensions to Google Maps components.

It extends Google Maps library functionalities by adding:

  • clustering,
  • heat maps,
  • and more:

You can add it to your project by adding this dependency:

dependencies {
    compile 'com.google.maps.android:android-maps-utils:0.4.3'
}