Not a subscriber?

Join thousands of others who are building self-directed lives through creativity, grit, and digital strategy—breaking free from the 9–5.
Receive one free message a week

Android: Centering text between two other Views

In this post I’ll show you how two use the layout_weight attribute in a LinearLayout to force an item so act as a “spring loaded view”. A picture is worth a thousand words.

Assume you have some dynamic text such as city name and your name. You need to display your name on the left and the city you’re from on the right hand side. In the middle you want to display a “bullet” separating the two text views. You can do that with the layout_weight attribute on the bullet text view. Here’s what you’re going after:

Spring weight sample

Now if the text grows on either side you want the bullet to remain in the middle. Here’s the code to do that:

The linear layout has filled the entire available area of the rounded corner LinearLayout (white background) and the text has a bullet exactly in the middle in the open space. I like to call this “spring loading” the middle view. By applying the “layout_weight” value of “1” to the bullet (\u2022 is unicode for the bullet) I have told the bullet to fill up all the available space it can and then I set the gravity of the bullet to center_horizontal. The gravity attribute informs the Android layout system to horizontally center any children of the TextView (the text inside of it). Now, if you were to change the text on either side from large or small you’d see that the bullet always remains in center available space.

This is very useful in areas where you have a ListView with a custom row and need the text to be dynamic yet uniform in layout (keep the same structure, but adapt dynamically on the size of the content).

Here’s what a few other options look like:

Spring loaded

Enjoy!