实现了显示文字的Gallery,效果如下:
首先肯定是创建android工程,修改res/layout下的main.xml文件如下:
<gallery android:id="@+id/mygallery" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:spacing="20dp" />
MainActivity中onCreate方法如下:、
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Gallery myGallery = (Gallery) findViewById(R.id.mygallery); SpinnerAdapter spinnerAdapter = new SimpleAdapter(this,getData(), android.R.layout.simple_gallery_item, new String[] {"mydata"},new int[] { android.R.id.text1 }); myGallery.setAdapter(spinnerAdapter);
解释一下SimpleAdapter的参数:
第一个adapter的View容器,第二个数据源,也就是显示在Gallery中的数据信息,类型是List,其中的枚举类型为Map,第三个gallery的layout布局,第四个数据源中Map的key,第五个为value的值盛放的view,这里用默认的android.R.id.text1 。
getData的方法如下:
public List getData(){ List myList = new ArrayList(); Map myMap = new HashMap(); myMap.put("mydata","aaa"); myList.add(myMap); myMap = new HashMap(); myMap.put("mydata","bbb"); myList.add(myMap); myMap = new HashMap(); myMap.put("mydata","ccc"); myList.add(myMap); myMap = new HashMap(); myMap.put("mydata","ddd"); myList.add(myMap); myMap = new HashMap(); myMap.put("mydata","eee"); myList.add(myMap); myList.add(myMap); return myList; }
到此,显示文字的Gallery就实现了。