我必须创建一个gridview,它载有来自SDCard上的特定文件夹的图像。该文件夹的路径是“/ sdcard / images /”。我试过这个代码,应用程序 加载时间过长,只显示一张图片。
public class ImAdapterh extends BaseAdapter{
File dir=new File(Environment.getExternalStorageDirectory(),"/myImages/");
int count=dir.list().length;
String[] fileNames = dir.list();
private Context mContext;
public ImAdapterh(Context c) {
mContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = null;
for(String bitmapFileName : fileNames)
{
if (convertView == null)
{ // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
Bitmap bmp = BitmapFactory.decodeFile(dir.getPath() + "/" + bitmapFileName);
System.out.println(dir);
imageView.setImageBitmap(bmp);
}else
{
imageView = (ImageView) convertView;
}
}
return imageView;
}
该应用占用了太多时间,而且只显示了一张图片
这是我的活动课
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImAdapterh(this));}
答案 0 :(得分:1)
该文件夹的路径是“/ sdcard / images /".
不,它不是,至少不适用于大多数设备。永远不要在Android中硬编码路径。始终使用Environment.getExternalStorageDirectory()
获取外部存储的根目录。
我尝试使用此代码,该应用程序花费了太多时间加载,并且它只显示一个图像。
当然。你在这里所做的事情是非常正确的。
最大的问题是,getView()
为ImageView
返回的每一行Adapter
将每个图片加载到同一个ImageView
。据推测,您应该只将一个图像加载到给定行的{{1}}中。
您的下一个最大问题是您正在主应用程序线程上执行磁盘I / O.
答案 1 :(得分:0)
从任何特定目录获取图像。使用以下代码
public void searchImageFromSpecificDirectory() {
String path = null;
String uri = MediaStore.Images.Media.DATA;
// if GetImageFromThisDirectory is the name of the directory from which image will be retrieved
String condition = uri + " like '%/GetImageFromThisDirectory/%'";
String[] projection = { uri, MediaStore.Images.Media.DATE_ADDED,
MediaStore.Images.Media.SIZE };
Vector additionalFiles = null;
try {
if (additionalFiles == null) {
additionalFiles = new Vector<String>();
}
Cursor cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
condition, null, null);
if (cursor != null) {
boolean isDataPresent = cursor.moveToFirst();
if (isDataPresent) {
do {
path = cursor.getString(cursor.getColumnIndex(uri));
System.out.println("...path..."+path);
additionalFiles.add(path);
}while(cursor.moveToNext());
}
if (cursor != null) {
cursor.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}