This is the first post in a new “How To” series in our blog. In this post I am going to show you how to justify the text of a CheckBox (or TextView) in Android. As you might know, an Android’s CheckBox is a view that includes a TextView and a box-shaped Button, which has different states such as pressed, not pressed and so on.
A default CheckBox in Android looks like this:
Android default CheckBox
One way to modify the space of between the Button and the TextView is to use “LeftPadding” attribute. This attribute lets developers add space between the Button and the TextView of a CheckBox. Although this might help us change the look of the CheckBox, it doesn’t solve the main problem:
1- “LeftPadding” attribute accepts a number and uses this number when drawing the CheckBox. Obviously, the number is a constant value and won’t be changed with respect to the size of the screen.
2- By adding space between the Button and the TextView, the text is still not justified. In fact, it gives us a view with two separated pieces. Believe me, it could be ugly!
Here is an example:
Android CheckBox with left padding
The main problem comes from the fact that Android TextView doesn’t provide the full justification feature. So if we replace the TextView with a WebView and ask the WebView to load a webpage that only shows a one-liner text, we might get it to work correctly. Since HTML supports text justification in tags like <div> or <p>, it is possible to enclose the text within a <div> tag (or <p>) and set its style to “Justify”. Although it looks reasonable, there is one more twist that we need to address. The problem is that although we have set the style of the div tag to “Justify”, if we have a one-liner text, the HTML thinks this is the last line of a paragraph and it shouldn’t be justified. Here is the trick; we can use a CSS style in our webpage and modify the default behavior of the div tag. Here is the HTML code of our webpage:
By using .fulljustify:after style, we can justify one-liner texts as well. Now we have our awesome CheckBox!
Android CheckBox with fully justified text
Here is the full code for the layout:
And here is the code for our activity class:
Android activity with customizable CheckBox