Android docs中的范例,简单翻译整理如下。
--------------------------------------------
1、创建新项目,名称HelloGallery;
2、准备一些图片文件,放到res/drawable/目录下;
3、修改res/layout/目录下main.xml,内容如下:
4、在res/values/目录下,新建文件attrs.xml,内容如下:
5、打开HelloGallery.java,修改后的代码如下:
6、运行项目,即可看到运行效果,如下图所示:
[img]http://dl.iteye.com/upload/attachment/428021/1d7a6bce-4fe3-31c3-8431-74262b78327f.png[/img]
--------------------------------------------
1、创建新项目,名称HelloGallery;
2、准备一些图片文件,放到res/drawable/目录下;
3、修改res/layout/目录下main.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
4、在res/values/目录下,新建文件attrs.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="HelloGallery">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>
5、打开HelloGallery.java,修改后的代码如下:
public class HelloGallery extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
// 图片资源的名称需要根据准备的图片名称进行修改
private Integer[] mImageIds = {
R.drawable.expo01, R.drawable.expo02, R.drawable.expo03, R.drawable.expo04, R.drawable.expo05,
R.drawable.expo06, R.drawable.expo07, R.drawable.expo08
};
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = a.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
}
6、运行项目,即可看到运行效果,如下图所示:
[img]http://dl.iteye.com/upload/attachment/428021/1d7a6bce-4fe3-31c3-8431-74262b78327f.png[/img]