最近在学习Gallery的SDK文档时,发现android的sdk文档关于Gallery的示例有一点小小的错误,在此贴上代码,以供学习的人来参考
首先先介绍一下Gallery,这是android中的 画廊 可以用来浏览图片,
一下是sdk中tutorial中的代码
1.在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" />
2.在Activity中代码如下,HelloGallery.java中代码如下:
@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();
}
});
}
3.在res/values/ 目录下创建一个 attrs.xml 文件,该文件指明了 画廊(Gallery)的背景框,没有此文件运行不过去
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="HelloGallery">
<attr name="android:galleryItemBackground"
/>
</declare-styleable>
</resources>
4.创建一个ImageAdapte.java类,该类用来填充 画廊(Gallery),也可以将此类作为内部类。对于用到的图片数组,网上下个让后跟数组里的名一样就行了。此处
我就不附加图片文件了
public
class ImageAdapter
extends BaseAdapter
{
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds
= {
R.drawable.sample_1,
R.drawable.sample_2,
R.drawable.sample_3,
R.drawable.sample_4,
R.drawable.sample_5,
R.drawable.sample_6,
R.drawable.sample_7
};
public ImageAdapter(Context c)
{
mContext = c;
//TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
//这是sdk中提供的函数,但是我在android 2.3中是编译不了的。
//此处我是改的,因为obtainStyledAttributes是Context所属的一个函数
TypedArray a
= mContext.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;
}
}
本文详细介绍了Android中Gallery组件的使用方法,并指出SDK文档中的一处错误实例,包括布局配置、Activity集成、自定义适配器及样式调整,旨在帮助开发者正确理解和应用Gallery组件。
6361

被折叠的 条评论
为什么被折叠?



