控件 -- GridView

一、概念

网格展示控件。

二、使用

1.基本属性

android:numColumns="auto_fit" 列数设置为自动
android:columnWidth="90dp" 每列的宽度,也就是Item的宽度
android:stretchMode="columnWidth" 缩放与列宽大小同步
android:verticalSpacing="10dp" 垂直边距
android:horizontalSpacing="10dp" 水平边距

2.例子

//activity_grid_view.xml



    


 
//item.xml



    
    


//Activity
public class GridViewActivity extends AppCompatActivity {
    private GridView gridView;
    private List> data_list;
    private SimpleAdapter adapter;
    private int[] icons = {R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher
            , R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher
            , R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher
            , R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher
            , R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher};
    private String[] text = {"111", "222", "333", "444", "555", "666", "777", "888", "999", "000", "123", "234", "345", "456", "555"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_view);

        gridView = (GridView) findViewById(R.id.gridView);
        data_list = new ArrayList>();
        getData();
        //加载适配器
        String[] form = {"image", "text"};
        int[] to = {R.id.image, R.id.text};
        adapter = new SimpleAdapter(this, data_list, R.layout.item, form, to);
        gridView.setAdapter(adapter);
        //监听item每一项
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int i, long l) {
                Toast.makeText(GridViewActivity.this, "你点击了第" + i, Toast.LENGTH_SHORT).show();
            }
        });
    }

    //准备数据源
    public List> getData() {

        for (int i = 0; i < icons.length; i++) {
            Map map = new HashMap();
            map.put("image", icons[i]);
            map.put("text", text[i]);
            data_list.add(map);
        }
        return data_list;
    }
}

你可能感兴趣的:(控件 -- GridView)