Android Learner Android Learner - 3 months ago 9
Android Question

Advantage of using single TableLayout instead of multiple LinearLayouts as TableRow extends LinearLayout only

My listview item consists of three columns and three rows.I used TableLayout for it.The space between columns was not uniform but i managed by setting margins.Now the layout looks perfect.

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/dp18"
android:paddingLeft="@dimen/dp16"
android:paddingTop="@dimen/dp18"
android:stretchColumns="0,1,2">
<TableRow>
..
</TableRow>
<TableRow>
..
</TableRow>
<TableRow>
..
</TableRow>
</TableLayout>


But I wonder was that ideal approach? What will be the difference in terms of optimization and performance if I have used four LinearLayouts(one outer horizontal linearlayout and three internal vertical linearlayout for three columns).As TableRow extends LinearLayout then indirectly I was using LinearLayout only..

Then,what is the Advantage of using single TableLayout instead of multiple LinearLayouts as TableRow extends LinearLayout only?

Answer

TableLayout is advantageous or LinearLayout is depends on the application and layout you require.

Well, you can achieve everything by LinearLayout, which you can get from TableLayout as it extends LinearLayout.

So, what’s the purpose of TableLayout?

Obviously, it gives more flexibility as you can arrange layout children into rows and columns. So, view looks more organize. Achieving such things by LinearLayout and its property like weight, orientation, margin, padding etc. is really tiresome.

Second difference is the methods setColumnShrinkable(), setColumnStretchable(), setColumnCollapsed() etc. introduce in TableLayout. Look at Documentation.

Again, these methods help to organize view and you can span columns /cell, as you can in HTML.

Example

Where TableLayout is useful compare to LinearLayout.

Consider a scenario when you want something like below: Full Detail Question

|img|leftText|rightText|                ||(end of screen)
|img|leftTextMedium|rightText|          ||
|img|leftTextTooLongSoTrunc...|rightText||

rightText must always appear on screen next to leftText no matter size of leftText. You can’t achieve something just by LinearLayout XML file (If you use weight property than it will add space between left and right text which is not desire output.)

You can achieve this easily by using android:shrinkColumns in TableLayout (check accepted answer in about mention question) but for LinearLayout you have to do some programming, XML won't works alone. Look here for code

I suppose you are now clear with the difference between above two Layouts.

Keep in mind that performance wise LinearLayout is better because TableLayout render more UI views and extends more methods. So, you should use TableLayout only when you require Row-Column behavior.