范例HelloGallery

Android docs中的范例,简单翻译整理如下。
--------------------------------------------
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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值