Search code examples
androiddynamicimageviewcenterandroid-tablelayout

How to center image dynamically in android table layout


I'm making an app and I'm dynamically adding TableRows which include 3 imageViews and one textview it looks like this (single tableRow):

IV1 --- TEXTVIEW ----- IV2 ----- IV3

(hope it will help to understand what I'm trying to achieve) I don't have any problem with centering TextView but I can't center ImageViews I was trying to do it like this:

TableLayout.LayoutParams tparams = newTableLayout.LayoutParams(
    TableLayout.LayoutParams.WRAP_CONTENT,
    TableLayout.LayoutParams.WRAP_CONTENT, 
    Gravity.CENTER_VERTICAL);
iv1.setLayoutParams(tparam);
iv2.setLayoutParams(fparams);
iv3.setLayoutParams(fparams);

but I'm getting erros wchich starts with that one:

11-06 16:37:06.809: E/AndroidRuntime(6578): java.lang.ClassCastException: android.widget.TableLayout$LayoutParams
11-06 16:37:06.809: E/AndroidRuntime(6578): at android.widget.TableRow.getColumnsWidths(TableRow.java:295) 
11-06 16:37:06.809: E/AndroidRuntime(6578): at android.widget.TableLayout.findLargestCells(TableLayout.java:500)
11-06 16:37:06.809: E/AndroidRuntime(6578): at android.widget.TableLayout.measureVertical(TableLayout.java:465)

Thanks for help


Solution

  • Try using TableRow.LayoutParams instead of TableLayout.LayoutParams. You are getting a class cast exception, which means that it's trying to cast your LayoutParams into the wrong type of LayoutParams. Since the views are actually children of the TableRow, not the TableLayout, you should use TableRow.LayoutParams.