1

I want to add custom view to a TableLayout with following code:

My custom view class:

public class MyCustomView extends View{
...
@Override
protected void onDraw(Canvas canvas) {
       super.onDraw(canvas);
      //draw on canvas      
   }
}

Added the view to table layout in another class:

public class MyTableView extends TableLayout{
....
private void AddViews(int column,int row){
    for (int i = 0; i < row; i++) {
        TableRow tableRows = new TableRow(mContext);
        for (int j = 0; j < column; j++) {
            MyCustomView myView= new MyCustomView();
            tableRows.addView(dayView);
        }
        addView(tableRows); 
    }

}

}

The table only displays first row:

| MyCustomView | MyCustomView | MyCustomView |

But if I change MyCustomView to inherit from TextView:

public class MyCustomView extends TextView

The table correctly displays all rows:

| MyCustomView | MyCustomView | MyCustomView |

| MyCustomView | MyCustomView | MyCustomView |

| MyCustomView | MyCustomView | MyCustomView |

What does the TextView have but the View doesn't which is causing the difference in TableLayout?

Should I add something to my custom view?

Note: I tried to set layout TableLayout.ParamLayout as LayoutParamater of the view, it doesn't work either.

Thanks.

barikatul
  • 171
  • 2
  • 13

1 Answers1

1

I found that I need to override onMeasure() in my custom view if I want to use WRAP_CONTENT for the custom view's layout param so that the parent layout which is the TableLayout can correctly recognize the height of the custom view and then display it correctly.

this post has great explanation for this.

Or by specifying the height of the custom view using layout param instead of using WRAP_CONTENT works also.

Community
  • 1
  • 1
barikatul
  • 171
  • 2
  • 13