【问题标题】:Android TableLayout contains custom view only displays first rowAndroid TableLayout 包含自定义视图只显示第一行
【发布时间】:2015-04-27 09:50:38
【问题描述】:

我想使用以下代码将自定义视图添加到 TableLayout:

我的自定义视图类:

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

将视图添加到另一个类的表格布局中:

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); 
    }

}

}

表格只显示第一行:

|我的自定义视图 |我的自定义视图 |我的自定义视图 |

但如果我将 MyCustomView 更改为从 TextView 继承:

public class MyCustomView extends TextView

表格正确显示所有行:

|我的自定义视图 |我的自定义视图 |我的自定义视图 |

|我的自定义视图 |我的自定义视图 |我的自定义视图 |

|我的自定义视图 |我的自定义视图 |我的自定义视图 |

TextView 有什么但 View 没有导致 TableLayout 的差异?

我应该在我的自定义视图中添加一些东西吗?

注意:我尝试将布局 TableLayout.ParamLayout 设置为视图的 LayoutParamater,它也不起作用。

谢谢。

【问题讨论】:

    标签: android android-custom-view android-tablelayout


    【解决方案1】:

    我发现如果我想将WRAP_CONTENT 用于自定义视图的布局参数,我需要在我的自定义视图中覆盖onMeasure(),以便作为 TableLayout 的父布局可以正确识别自定义视图的高度和然后正确显示。

    this post 对此有很好的解释。

    或者通过使用布局参数而不是使用WRAP_CONTENT 来指定自定义视图的高度也可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 2011-08-26
      相关资源
      最近更新 更多