Android GridView imperfection, how to remove extra white space to the right

ε祈祈猫儿з 提交于 2019-12-04 07:47:58
dinesh sharma

This space is due to imperfect calculation for each row of your grid. For example your device width is 320 px and you have 7 rows, try any calculation that meets 320 px. If the width of each cell is 45.71428571428571 px, only then it can be reduced.

Other option

apply android:gravity="center" property in you grid so that spaces will equally divided from left to right

in my case I had horizontal spacing as 1dp

android:horizontalSpacing="1dp"

so to solve this I just put the right padding as -1dp

android:paddingRight="-1dp"

even though I expected to get a space on the left side due to this , but it worked properly

Try using

android:layout_margin="0dp"
android:padding="0dp"

Also you might have that space allocated for the scroll bar.
And why do you have your vertical and horizontal spacing with negative values?

I had the same problem though in my case I didn't have control over the GridView instance so I couldn't read the column width. Nevertheless I could subclass its container.
This isn't very orthodox but you can override the onMeasure method and add a few pixels.
Something like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int RIGHT_MARGIN_OVERSIZE_DIP = 6;
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = this.getMeasuredWidth()
    int overSize = (int)((getResources().getDisplayMetrics().density*RIGHT_MARGIN_OVERSIZE_DIP) + 0.5f);
    widthMeasureSpec = MeasureSpec.makeMeasureSpec(width + overSize, MeasureSpec.getMode(widthMeasureSpec));        
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
grid.setColumnWidth(grid.getColumnWidth()+1);

This will get the current ColumnWidth and add 1 pixel to it. Remember to use this after onCreateView,since the grid needs to be initialized before that.

Also,your grid view,should use match_parent (height and width).The image/layout in the column should be also match_parent.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!