我已将自定义视图定义为 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 中获取屏幕尺寸并不是一件非常准确的事情。
那么我应该如何以编程方式创建网格布局?