Justifying text inside TextView in Android is not that simple as we may expect it to be. Unfortunately, Android does not have attribute for TextView, which supports justifying text. We can set alignment to the right or to the left, but we cannot simply justify text with generic attributes. In order to do that, we need to perform a few tricks.
First of all, we need to create file named justified_textview.css and we need to put it into the assets/ directory of our project. We will use it later in our custom view. Source code of this CSS stylesheet is presented below:
Next, we need to create class for customized view extending WebView. Let’s call it JustifiedTextView.
After that, we need to update res/values/attrs.xml file and put inside the following declaration:
Now, we are ready to use our custom JustifiedTextView.
In order to do that, we need to create layout containing JustifiedTextView as follows:
Next, we can access JustifiedTextView in our activity:
We can also set text inside XML layout instead of doing this programmatically. It depends on our project.
We also should turn off hardware acceleration for given activity in AndroidManifest.xml file in order to bring this solution to work.
That’s it. It’s not perfect solution and it’s kind of workaround, but I haven’t found any better idea how to deal with this problem.
I tested a few solutions and this one is, in my opinion, the best available and most elegant option for now.
Please note: There may be a problem with proper execution of this solution on Android OS version lower than 3.0 (API 11).
If you know any better ideas, how to deal with this problem, please let me know about that in comments below this article.