Android基础——网格视图和适配器
额外新建一个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); } }
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28