Android杂谈--ListView之BaseAdapter的使用二(转)
实例二:Gallery上应用BaseAdapter
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/img"
android:layout_width="480px"
android:layout_height="480px"
android:layout_gravity="center"
/>
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spacing="3dp"
android:layout_gravity="bottom"
/>
</LinearLayout>
Activity:这部分里的getView没有优化,调试了很久还没调通,暂时还是用的最基本的方法。会专门找个时间把Gallery内存泄露的部分写一下,因为图片资源很多的时候会引起out of memory的错误
package com.loulijun.demo16;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
public class Demo16Activity extends Activity {
private Gallery mGallery;
private ImageView mImg;
//图片数组
private int[] pics = {
R.drawable.pic1,
R.drawable.pic2,
R.drawable.pic3,
R.drawable.pic4,
R.drawable.pic5,
R.drawable.pic6
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImg = (ImageView)findViewById(R.id.img);
mGallery = (Gallery)findViewById(R.id.gallery);
MyAdapter adapter = new MyAdapter(this);
mGallery.setAdapter(adapter);
mGallery.setOnItemClickListener(new Gallery.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position,
long arg3) {
mImg.setImageResource(pics[position]);
}
});
}
//内部类
class MyAdapter extends BaseAdapter
{
//用来接收传递过来的Context上下文对象
private Context context;
//构造函数
public MyAdapter(Context context)
{
this.context = context;
}
@Override
public int getCount() {
//返回图片数组大小
return pics.length;
}
@Override
public Object getItem(int position) {
//根据选中项返回索引位置
return position;
}
@Override
public long getItemId(int position) {
//根据选中项id返回索引位置
return position;
}
//未优化的getView,这部分可以使用recycle()释放内存、或者BitmapFacotry.Options缩小,或者软引用,或者控制图片资源大小等等很多方法,找时间专门写
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView img = new ImageView(context);
img.setAdjustViewBounds(true);
img.setImageResource(pics[position]);
img.setScaleType(ImageView.ScaleType.FIT_XY);
img.setLayoutParams(new Gallery.LayoutParams(120,120));
return img;
}
}
}
运行效果:原理都是一样,只不过是布局加载的时候会有区别,不过就这个小区别也让人够恼火的了