一、在新建GridView模块下添加图片以及创建cell.xml文件
1.粘贴图片时选择红框中的路径,点击“OK”
2.在路径后添加-mdpi后缀,再点击“OK”
二、相关代码块
1.MainActivity.java文件代码
package com.example.gridview;import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;
import android.widget.GridView;
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.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};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);GridView gridView = (GridView) findViewById(R.id.gridview);List<Map<String ,Object>> listitem = new ArrayList<Map<String,Object>>();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 = new SimpleAdapter(this,listitem,R.layout.cell,new String[]{"image"},new int[]{R.id.image});gridView.setAdapter(simpleAdapter);}
}
2.activity_main.xml文件代码
<?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"><GridViewandroid:id="@+id/gridview"android:layout_width="match_parent"android:layout_height="match_parent"android:numColumns="3"></GridView></RelativeLayout>
3.cell.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"><ImageViewandroid:id="@+id/image"android:layout_width="100dp"android:layout_height="75dp"/></LinearLayout>
四、运行结果