【Android】GridView添加网格线

GridView网格布局,默认情况下是没有网格线的

查找网上资料,找到了一种为GridView添加网格线的小技巧

 

实际上,该网格线是通过设置GridView各子项的间隔,并分别设置GridView背景色与子项背景色实现的。

 

实现方法

 

  1. 设置GridView背景色,设置水平间方向间隔属性值android:horizontalSpacing和竖直方向间隔属性值android:verticalSpacing
  2. 设置GridView子项背景色
示例代码:
main.xml



Main.java
package dyingbleed.iteye;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

public class Main extends Activity {
	
	private GridView grid;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        grid = (GridView) findViewById(R.id.main_GridView);
        grid.setAdapter(new GridViewAdapter(this));
    }
    
    private class GridViewAdapter extends BaseAdapter {
    	
    	private Context context;
    	
    	public GridViewAdapter(Context context) {
    		this.context = context;
    	}
    	
    	int count = 100;

		@Override
		public int getCount() {
			return count;
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView result = new TextView(context);
			result.setText("Item "+position);
			result.setTextColor(Color.BLACK);
			result.setTextSize(24);
			result.setLayoutParams(new AbsListView.LayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)));
			result.setGravity(Gravity.CENTER);
			result.setBackgroundColor(Color.WHITE); //设置背景颜色
			return result;
		}
    	
    }
}
  
运行截图:
【Android】GridView添加网格线_第1张图片

你可能感兴趣的:(Android界面)