Android_遍历SD卡中某一路径下指定类型的图片
遍历SD卡中某一路径下指定类型的图片
1.Activity
public class TextActivity extends Activity {
Gallery g = null;
List<String> it = null;// 遍历符合条件的列表
public String actionUrl = null;
private final String SD_PATH = android.os.Environment
.getExternalStorageDirectory().getAbsolutePath();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location_photo);
g = (Gallery) findViewById(R.id.mygallery);
//添加一个ImageAdapter并设置给Gallery对象
g.setAdapter(new ImageAdapter(this, getSD()));
//设置一个itemclickListener并Toast被单击图片的位置
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(TextActivity.this,
"序列:" + (position + 1) + "\n路径:" + it.get(position),
Toast.LENGTH_LONG).show();
}
});
}
//遍历SD卡中某一路径下指定类型的图片
private List<String> getSD() {
it = new ArrayList<String>();
File f = new File(SD_PATH + "//" + "picture");
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (getImageFile(file.getPath()))
it.add(file.getPath());
}
return it;
}
//指定遍历文件类型
private boolean getImageFile(String fName) {
boolean re;
String end = fName
.substring(fName.lastIndexOf(".") + 1, fName.length())
.toLowerCase();
if (end.equals("jpg") || end.equals("gif") || end.equals("png")
|| end.equals("jpeg") || end.equals("bmp")) {
re = true;
} else {
re = false;
}
return re;
}
//改写BaseAdapter自定义一ImageAdapter class
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private List<String> lis;
public ImageAdapter(Context c, List<String> li) {
mContext = c;
lis = li;
//使用在res/values/aatrs.xml中的<declare-styleable>定义
TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
//取得Gallery属性
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery_android_galleryItemBackground, 0);
//让对象的styleable属性能够反复使用
a.recycle();
}
//重写的方法,返回图片数目
public int getCount() {
return lis.size();
}
//重写的方法,返回图片的数组id
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//重写的方法,返回一View对象
public View getView(int position, View convertView, ViewGroup parent) {
//产生ImageView对象
ImageView i = new ImageView(mContext);
//设置图片给ImageView对象
Bitmap bm = BitmapFactory.decodeFile(lis.get(position).toString());
i.setImageBitmap(bm);
//重新设置图片的宽度
i.setScaleType(ImageView.ScaleType.FIT_XY);
//重新设置Layout的宽度
i.setLayoutParams(new Gallery.LayoutParams(188, 288));
//设置Callery背景图
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
}
2.attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Gallery">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>