您的位置:首页 > 移动开发 > Android开发

Android遍历某个文件夹的图片并实现滑动查看的的Gallery

2012-06-26 21:37 417 查看


关键代码一个adapter

package com.su.houses.utils;

import android.content.Context;
import android.content.res.TypedArray;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

import com.su.houses.R;

public class ImageAdapter extends BaseAdapter {
private Context mContext;
public String picpath;
private String[] myImageNames;

public ImageAdapter(Context c, String path) {

mContext = c;
picpath = path;

myImageNames = FileUtil.getImageNames(picpath);

}

public int getCount() {

return myImageNames.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

public View getView(int position, View convertView, ViewGroup parent) {

ImageView imageView = new ImageView(mContext);
imageView.setImageURI(Uri.parse(picpath + "/" + myImageNames[position]));
imageView.setLayoutParams(new Gallery.LayoutParams(800, 600));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

return imageView;
}

}

然后其中的一些方法

public static String[] getImageNames(String folderPath) {
File file01 = new File(folderPath);

String[] files01 = file01.list();

int imageFileNums = 0;
for (int i = 0; i < files01.length; i++) {
File file02 = new File(folderPath + "/" + files01[i]);

if (!file02.isDirectory()) {

if (isImageFile(file02.getName())) {

imageFileNums++;
}
}
}

String[] files02 = new String[imageFileNums];

int j = 0;
for (int i = 0; i < files01.length; i++) {
File file02 = new File(folderPath + "/" + files01[i]);

if (!file02.isDirectory()) {

if (isImageFile(file02.getName())) {
files02[j] = file02.getName();
j++;
}
}
}
return files02;
}

private static boolean isImageFile(String fileName) {
String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1,
fileName.length());
if (fileEnd.equalsIgnoreCase("jpg")) {
return true;
} else if (fileEnd.equalsIgnoreCase("png")) {
return true;
} else if (fileEnd.equalsIgnoreCase("bmp")) {
return true;
} else {
return false;
}
}

然后在实例化adapter在界面的gallery显示

Gallery g = (Gallery) findViewById(R.id.house_gallery);
g.setAdapter(new ImageAdapter(this,"/mnt/sdcard/k/a/"));

也可以添加listener

g.setOnItemSelectedListener(new OnItemSelectedListener()
{
// 选择图片的事件
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id)
{
// 获取当前图片文件名
currentImageName = myImageNames[position];
// 获取当前图片路径
currentImagePath = currentFolderPath + "/" + currentImageName;
// 设置imageSwitcher的显示图片
}

public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: