Android基础——网格视图和适配器

csdnuuu 2020-01-25

额外新建一个layout,用来布局ImageView组件

<?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="75dp"
        android:id="@+id/imageView"
        />
</LinearLayout>

网格视图的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3">
</GridView>


    </RelativeLayout>

java的调用,使用了适配器SimpleAdapter,将ImageView通过适配器交给GridView

package com.example.myhighuiiii;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private int[] picture = new int[]{
            R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d
    };
    ImageView imageView = null;
    GridView gridView = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gridView = (GridView) findViewById(R.id.gridView);
        //用一个List来存图片对象
        List<Map<String,Object>> listItem = new ArrayList<Map<String, Object>>();
        //把map对象添加到list中
        for(int i=0;i<picture.length;i++){
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("image",picture[i]);
            listItem.add(map);
        }
        //创建simpleAdapter对象
        SimpleAdapter simpleAdapter = new SimpleAdapter(//构造器总共有五个参数
                this,listItem,R.layout.celi,new String[]{"image"},new int[]{R.id.imageView});
        //为网格视图设置适配器
        gridView.setAdapter(simpleAdapter);
    }
}

相关推荐