可以正确显示表格线的Grid item view

时间:2023-12-10 20:36:50

Android上要显示一个表格,没有Swing那么专门的JTable可用。

搜了下,一般用GridView,有诸多不便和需要自己实现的地方:

跟ListView一样的Adapter,getView的时候要把表格的二维空间转换成一维来返回。如果表格要画线,问题就来了,返回的Cell View处在一维中的,压根不知道自己在表格中的位置,所以不知道要绘制自己的哪根边界线。于是我封装了一个Cell View的View holder,传入count, column count, position,会根据自己所处的位置自动隐藏/展示上下左右四条边界线。

所有代码在Gist: Grid item view holder for GirdView which show the border lines properly.

https://gist.github.com/Viyu/3af499b51318128d1aab

核心代码:

public void setLineVisible(int totalCount, int columnCount, int position) {

// 只有一个item

if (totalCount < 2) {

mTopLine.setVisibility(View.VISIBLE);

mBottomLine.setVisibility(View.VISIBLE);

mLeftLine.setVisibility(View.VISIBLE);

mRightLine.setVisibility(View.VISIBLE);

return;

}

// 只有一行

if (totalCount == columnCount) {

mTopLine.setVisibility(View.VISIBLE);

mBottomLine.setVisibility(View.VISIBLE);

mRightLine.setVisibility(View.VISIBLE);

if (position == 0) {// 第一个

mLeftLine.setVisibility(View.VISIBLE);

} else {// 后面的

mLeftLine.setVisibility(View.GONE);

}

return;

}

// 只有一列

if (columnCount < 2) {

mLeftLine.setVisibility(View.VISIBLE);

mRightLine.setVisibility(View.VISIBLE);

mBottomLine.setVisibility(View.VISIBLE);

if (position == 0) {// 第一个

mTopLine.setVisibility(View.VISIBLE);

} else {// 后面的

mTopLine.setVisibility(View.GONE);

}

return;

}

// 至少两行两列

if (position == 0) {// 0, 0

mLeftLine.setVisibility(View.VISIBLE);

mRightLine.setVisibility(View.VISIBLE);

mTopLine.setVisibility(View.VISIBLE);

mBottomLine.setVisibility(View.VISIBLE);

} else if (position / columnCount == 0) {// 第一行

mLeftLine.setVisibility(View.GONE);

mRightLine.setVisibility(View.VISIBLE);

mTopLine.setVisibility(View.VISIBLE);

mBottomLine.setVisibility(View.VISIBLE);

} else if(position % columnCount == 0) {//第一列

mLeftLine.setVisibility(View.VISIBLE);

mRightLine.setVisibility(View.VISIBLE);

mTopLine.setVisibility(View.GONE);

mBottomLine.setVisibility(View.VISIBLE);

} else {//其他的

mLeftLine.setVisibility(View.GONE);

mRightLine.setVisibility(View.VISIBLE);

mTopLine.setVisibility(View.GONE);

mBottomLine.setVisibility(View.VISIBLE);

}

}