利用GridView来做一个简单的图片查看器

        首先简单说明一下实现这个简单的图片查看器,我们需要做些那些工作,实现图片查看器我们应该第一先到要用到的是适配器(Adapter)一下是adpter的构造函数,

SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) 从构造函数我们可以看出他告诉我们要实现他我们需要给他传一个context上下文的参数 ,list数据源数组,resource数据源文件用来显示List中一条数据的布局文件,String[] HashMapKey的值,int[]to 元素中布局文件中的试图id (应为)这里图片肯定不只一张需要用数组来保存;

显示GridVeiwdlayout

    <GridView

        android:id="@+id/gridView"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:horizontalSpacing="10dp"

        android:numColumns="4"

        android:padding="10dp"

        android:verticalSpacing="100dp"

扫描二维码关注公众号,回复: 516842 查看本文章

/>

//这个GridVeiw控件的是四列组成 内边距是10dp水平间隔也是100dp

显示图片和备注的layout

    <ImageView

        android:id="@+id/img"

        android:layout_width="50dp"

        android:layout_height="50dp"

       />

 

    <TextView

        android:id="@+id/text"

        android:layout_width="50dp"

        android:layout_height="wrap_content"

        android:gravity="center_horizontal"

       />

//这个layout就是一个ImgeVeiwTextVeiw控件属性也比较简单这里我不多说了

这个在MainActivity需要实现的代码

       private GridView gridView;

       static int[] imgs = { R.drawable.a1, R.drawable.a2, ………};

       //这个数组的作用是存放的图片,这个我了叙述简单就直接将突破存放在res.drawable-hdpi下面,当然在实际的项目中图片的存放有可能是一个url路径,或者是CD卡。

@Override

       protected void onCreate(Bundle savedInstanceState) {

              super.onCreate(savedInstanceState);

              this.setContentView(R.layout.activity_third);

 

              // 获得网格视图

              gridView = (GridView) this.findViewById(R.id.gridView);

 

              // 数据源

              ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

 

              for (int i = 0; i < imgs.length; i++) {

HashMap<String, Object> map = new HashMap<String,Object>();

                     map.put("k1", imgs[i]);

                     map.put("k2", "程序" + i);

                     data.add(map);

              }

 

              String[] from = { "k1", "k2" };

              int[] to = { R.id.img, R.id.text };

              // 参数1:上下文

              // 参数2:数据

              // 参数3:用来显示List中一条数据的布局文件

              // 参数4HashMapK的数组  

              // 参数5:元素的布局文件中的视图id

              SimpleAdapter adapter = new SimpleAdapter(this, data,

                            R.layout.grid_item, from, to);

              gridView.setAdapter(adapter);

       //设置这个适配器

       }

 

       效果图:

       

 

这就是一个简单的图片查看器 很简单 大家去试一试吧。。。

猜你喜欢

转载自hit-me.iteye.com/blog/2172961