[英]How to set an Android GridView with different column sizes
我的主布局中有一個GridView,如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:horizontalSpacing="1dp"
android:stretchMode="columnWidth"
android:verticalSpacing="1dp" />
</LinearLayout>
產生像這樣的網格
每個單元格的內容都是這樣的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="@drawable/btn_measurement" >
<Button
android:id="@+id/numerical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="---" />
</LinearLayout>
但是我希望第4列是其他列的三分之一,但我不能。
我檢查了鏈接:
具有不同列大小的 GridView和Android GridView列拉伸
但是他們沒有幫助。 :(
如果您認為我需要完全改變我的解決方案,請比提供一般性提示更為精確。 謝謝
使用此代碼可以減小列的大小,但在這里必須應用一些邏輯。 您希望它的第4列較小,因此您必須重寫getView()方法,然后使用use變量,並檢查該變量是3還是7或11 ...然后將button的尺寸減小。 我想你明白我的意思了...
int logic =3;
public View getView(int position, View convertView, ViewGroup parent) {
Button btn;
LinearLayout layout;
if (convertView == null) {
convertView = inflate the layout and initialize convertview
if(position % logic==0)
converView..setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT,
(float) 0.3));
btn = new Button(context);
btn.setGravity(Gravity.RIGHT);
btn.setPadding(5, 5, 5, 5);
layout = new LinearLayout(context);
layout.setOrientation(0);
layout.setPadding(5, 5, 5, 10);
btn.setText(names[position]);
layout.addView(btn);
}
else {
layout = (LinearLayout) convertView;
btn = (Button) layout.getChildAt(0);
btn.setText(names[position]);
}
return layout;
}
將RecyclerView(而不是GridView)與自定義GridLayoutManager一起使用,如“可變范圍大小”下所示: http : //blog.sqisland.com/2014/12/recyclerview-grid-with-header.html
您基本上將使每個常規列占用3倍,而較小的列占用1倍。
GridLayoutManager manager = new GridLayoutManager(this, 10); // 3 cols of 3 + 1 col of 1
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if (position % 4 == 3)
return 1; // Fourth column is 1x
else
return 3; // Remaining columns are 3x
}
});
recyclerView.setLayoutManager(manager);
我曾經使用這個解決方案
通過使用列表視圖而不是網格視圖,並為每個項目在一個水平線性布局中放置4個按鈕。 但是您需要額外的工作來檢測按鈕的單擊,但是我認為這是可行的
我可以找到的另一項工作是使用第3方庫,例如https://github.com/felipecsl/AsymmetricGridView
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.