移动应用开发之高级布局(网格布局)

效果

移动应用开发之高级布局(网格布局)_第1张图片

步骤一、

activity main.xml中定义

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <GridView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/grid01"
        android:numColumns="3"
        android:gravity="center"
        android:stretchMode="columnWidth"
        android:verticalSpacing="20dp" />
</LinearLayout>

步骤二、

创建新的布局文件 grid_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:id="@+id/itemImage" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/itemText" />
</LinearLayout>

步骤三、mainactivity中加载

private int images[] = null;
    private String texts[] = null;
    private GridView grid1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        grid1 = (GridView) findViewById(R.id.grid01);
        images = new int[] {R.drawable.p1, R.drawable.p2, R.drawable.p3, R.drawable.p4, R.drawable.p5, R.drawable.p6, R.drawable.p7, R.drawable.p8, R.drawable.p9};
        texts = new String[] {"选项1", "选项2", "选项3", "选项4", "选项5", "选项6", "选项7", "选项8", "选项9"};
        List<HashMap<String, Object>> itemList = new ArrayList<HashMap<String, Object>>();
        for (int i=0; i<9; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("itemImage", images[i]);
            map.put("itemText", texts[i]);
            itemList.add(map);
        }
        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, itemList, R.layout.grid_item, new String[] {"itemImage", "itemText"}, new int[] {R.id.itemImage, R.id.itemText});
        grid1.setAdapter(adapter);
		
		//gid1添加监听事件
        grid1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int option = position + 1;
                Toast.makeText(MainActivity.this, "你选择了选项" + option, Toast.LENGTH_SHORT).show();
            }
        });

你可能感兴趣的:(移动应用)