[英]How to create an n x 2 grid programmatically in Android Java code?
我已經將自定義視圖定義為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
我應該如何實現這樣的目標?
並且請注意,我用Java代碼(而不是XML)構造CustomView
。
我嘗試獲取屏幕尺寸,將其除以n,然后將值分配為自定義視圖的LayoutParams.width
。
但是,根據StackOverflow中的一些問題,獲得dp的屏幕尺寸並不是很准確的事情。
那么我應該如何以編程方式創建網格布局?
為什么在這種情況下不使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.