Gallery画廊式控件,如图所示,但是在API level 16,也即Android 4.1,被deprecated,可以使用HorizontableScroolView和ViewPager。但是后来者都不是AdapterView,所有我们仍快速地略过Gallery,也顺带学习一下SimpleAdapter。

XML layout文件如下:

<?xml version="1.0" encoding="utf-8"?> 
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ui_gallery" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    />

对于子view,有预置android.R.layout.simple_gallery_item,但那是TextView,不符合我们的要求,我们需要的是ImageView,故自行设置子view的布局,ui_imageitem.xml文件如下:

<?xml version="1.0" encoding="utf-8"?> 
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ui_imageItem" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:ellipsize="marquee" />   <!-- 当字符内容太长显示不下时可以省略号代替未显示的字符;省略号可以在显示区域的起始,中间,结束位置,或者以跑马灯的方式显示文字,截图显示的就是marquee方式。  -->

SimpleAdapter经常用于静态资源。适合用于gallery。下面的Java代码:

public class UiGalleryTest extends Activity{ 
    /* int[] pics对应我们在res/drawable/下的图片资源,picsName对应他们的key,我们在此特地将第二个资源的key设为不一样。在最后的结果重,我们可以看到第二章图片没有在gallery中显示 */
    private int[] pics = {R.drawable.sunflower01, R.drawable.sky01,R.drawable.sky02};
    private String[] picsName = {"image","image1","image"}; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.ui_gallery);          
        @SuppressWarnings("deprecation") 
        Gallery gallery = (Gallery)findViewById(R.id.ui_gallery);
        //SimpleAdapter的数据源的格式是List<?extends Map<String ?>>,这个格式写法比较特别,它是list of Map,每个entry就是一个数据单位。 
        ArrayList<HashMap<String,Object>> images = new ArrayList<HashMap<String,Object>>();
        for(int i = 0 ; i < pics.length; i ++){ 
            HashMap<String,Object> one = new HashMap<String, Object>();  
            one.put(picsName[i], Integer.valueOf(pics[i])); 
            images.add(one);  
        }  
        //SimpleAdapter和其他的adapter差不多,参数很容易理解                 
        SimpleAdapter adapter = new SimpleAdapter(this /*context*/, images /*数据源*/,  
               R.layout.ui_imageitem,  /* 子View的layout,有预置android.R.layout.simple_gallery_item,但那是TextView,不符合我们的要求 */ 
               new String[]{"image"},  // 从Map中选取数据,本例即哪个key,我们选取“image”,故不显示第二个图
               new int[]{R.id.ui_imageItem}); //子view中控件ID
        gallery.setAdapter(adapter); 
    } 
}

相关链接: 我的Android开发相关文章