##此方法是使用自带适配器实现
gridview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_horizontal"
/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">
<!--
android:numColumns="3"三列
android:stretchMode="spacingWidthUniform"
加入参数后gridview内的组件长宽需要设定具体值,否指无法正常显示
columnWidth 如果列有空闲空间就加宽列
spacingWidth 如果列有空闲空间就加宽各列间距
none 没有任何动作
spacingWidthUniform 平均分配空间
-->
<GridView
android:id="@+id/gv1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
>
</GridView>
</android.support.constraint.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private GridView gridView;
private SimpleAdapter adapter;
private List<Map<String,Object>>data;
String[] from={"img","text"};
int[] to={R.id.img1,R.id.text1};
private int img1=R.drawable.tou; //此为图片地址
private String text1[]={"1","2","3","4"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
data=new ArrayList<Map<String,Object>>();
for(int i=0;i<text1.length;i++){
Map<String,Object>map=new HashMap<>();
map.put("img",img1);
map.put("text",text1[i]);
data.add(map);
}
gridView=findViewById(R.id.gv1);
// public SimpleAdapter(Context context, List<? extends Map<String, ?>> data,
// @LayoutRes int resource, String[] from, @IdRes int[] to)
// 上下文,一个List里面含有Map,来源的第三个xml,map里面的String标签数列,要一一对一个,
// 里面的组件数列
adapter=new SimpleAdapter(this,data,R.layout.gridview,from,to);
gridView.setAdapter(adapter);
}