Sunday, 23 December 2012

How to set weight in linearlayout in Android

Today I was writing an app on Android. There was a LinearLayout with 3 TextViews which fill the screen. I wanted their width to be 1:6:6. So I set the "android:layout_weight" property 1, 6, 6. But it didn't work that way. The first TextView became very big and the other two become very small. Then I guess the "weight" means importance. The smaller the weight is, the larger it will be. So I read a lot and found this method to set the weights of the components in your app:
1. Suppose the size of the screen is X.
2. Count how many views there are in a LinearLayout, here I use my example, 3.
3. Total width: total = 3X.
4. delta = X - total = -2X.
5. Suppose you set the weight of the first TextView to be A.
6. Suppose you want the TextView to be 1/13 of the width of the screen.
7. Then use this formula to solve the value of 'A':  X + delta*(A/13) = (1/13)X , A=6

I did like this and got the three weight values: 6, 3.5, 3.5, and I got the result exactly as I wanted, the width of the three TextView is 1:6:6.

No comments:

Post a Comment