在手机应用中看到好多带有分割线的GridView,但android的GridView并没有设置分割线的属性。网上找到的资料就是重写GridView。效果如下:
代码如下:
public class GridViewLine extends GridView {
private static final String TAG = "GridViewLine";
private int mColor=Color.LTGRAY;
public GridViewLine(Context context) {
super(context);
}
public GridViewLine(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GridViewLine(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setLineColor(int color){
this.mColor=color;
}
int i=0;
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
//获取列数
int columns=getNumColumns();
//获取子类总数
int counts=getChildCount();
Paint paint=new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(mColor);
int no_lin=counts%columns==0?columns:counts%columns;
for (int i = 0; i <counts ; i++) {
View view=getChildAt(i);
//底线
if(i<(counts-no_lin)){
canvas.drawLine(view.getLeft(),view.getBottom(),view.getRight(),view.getBottom(),paint);
}
//右线
if((i+1)%columns!=0){
canvas.drawLine(view.getRight(),view.getTop(),view.getRight(),view.getBottom(),paint);
}
}
}
}
Activity
public class MainActivity extends AppCompatActivity {
private GridViewLine gridViewLine;
private List<Integer> images;
private List<Map<String,Integer>> maps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
images=new ArrayList<>();
maps=new ArrayList<>();
InitData();
gridViewLine =(GridViewLine)findViewById(R.id.gridview);
// gridViewLine.setLineColor(Color.RED);
SimpleAdapter simpleAdapter=new SimpleAdapter(this,maps,R.layout.gridview_item,new String[]{"image"},new int[]{R.id.image});
gridViewLine.setAdapter(simpleAdapter);
gridViewLine.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,"Click "+i,Toast.LENGTH_SHORT).show();
}
});
}
private void InitData() {
images.addAll(Arrays.asList(R.drawable.ic_device_model_htc,R.drawable.ic_device_model_huawei,R.drawable.ic_device_model_iphone,
R.drawable.ic_device_model_ktouch,R.drawable.ic_device_model_lg,R.drawable.ic_device_model_meizu));
for(int i=0;i<images.size();i++){
Map<String,Integer> map=new HashMap<>();
map.put("image", images.get(i));
maps.add(map);
}
}