0

我已将自定义视图定义为 Java 类,现在我想以编程方式将它们放入布局中。

我可以定义这样的布局结构:

<LinearLayout> <!-- vertical, main container -->

    <LinearLayout> <!-- 1st horizontal (consists of 2 columns (items) ) -->
        <CustomView /> <!-- 1 -->
        <CustomView /> <!-- 2 -->       
    </LinearLayout>

    <LinearLayout> <!-- 2nd horizontal (consists of 2 columns (items) ) -->
        <CustomView /> <!-- 1 -->
        <CustomView /> <!-- 2 -->
    </LinearLayout>

    <!-- ..... -->
    <LinearLayout> <!-- nth horizontal (consists of n columns (items) ) -->
        <CustomView /> <!-- 1 -->
        <CustomView /> <!-- 2 -->
    </LinearLayout>




</LinearLayout><!-- vertical container -->

但是当我删除其中一个自定义视图时,它仍然很难看。假设 n=3 并且我删除了自定义视图编号 4。我有:

1 2
3 
5 6

这看起来不太好,他们应该像这样“填充前导空间”:

1 2
3 5
6

我应该如何实现这样的事情?

请注意,我CustomView在 Java 代码中构造了 s(不是在 XML 中)

我尝试获取屏幕大小,将其除以 n,然后将值分配为LayoutParams.width自定义视图的值。

但是根据 StackOverflow 中的一些问题,在 dp 中获取屏幕尺寸并不是一件非常准确的事情。

那么我应该如何以编程方式创建网格布局?

4

1 回答 1

0

为什么在这种情况下不使用 GridView?

您可以根据集合中的项目来减小 GridView 的大小,

int NUM_COLUMNS = 5;
double NUM_ROWS = items.size() / NUM_COLUMNS; // calculate no. of rows.
double calculateHeight;
if(items.size() % 5 == 0){ // 5, 10, 15, 20...
    calculateHeight = ((NUM_ROWS) * height of required gridview row) + 50; 
                                                        // adding 50 for spacing.
}
else{ // 1,2,3,4,6,7,8,9,11...
    calculateHeight = ((NUM_ROWS + 1) *  height of required gridview row) + 50; 
                                                        // adding 50 for spacing.
}
mGridView.getLayoutParams().height = (int) calculateHeight; // setting 
                                                     the final Height of GridView
于 2013-11-13T09:11:33.383 回答