最近在学习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;
}
}

更多相关文章

  1. Android打包成jar文件方法总结
  2. Linux手机打电话代码分析
  3. android 应用程序包文件 (APK)
  4. Android 动态加载布局文件
  5. android 工程里缺少 R.java 文件原因和解决方法
  6. 使用pull解析器操作xml文件
  7. 解决android一直在running,打不开文件,下载不了gradle包的方法
  8. 【android开发】解析xml文件①
  9. 巧用布局文件实现Android中实现事件监听机制

随机推荐

  1. Ubuntu下搭建Android开发平台
  2. Android手机客户端通过JSP实现与Tomcat服
  3. Android自绘字体大小paint.settextsize随
  4. Handler sendMessage 与 obtainMessage (
  5. android中的hdpi,ldpi,mdpi
  6. layout_weight详解
  7. Android(安卓)so 文件全部报错:Duplicate
  8. Android(安卓)Camera 四 Camera HAL 分析
  9. Android常见控件使用经验之——Activity
  10. 【Android】获取手机中已安装apk文件信息