相对较新的Android和初学者使用Gallery功能。话虽如此,在我的应用程序中,我将图像保存在图库文件夹(Gallery / MyAppFolder)中。我在GridView中显示这些文件夹。到这里它正如预期的那样正常工作。现在我试图在gridview上实现一个点击监听器,它应该显示该特定图像。以下是我在我的活动中尝试实现上述目标的代码
public String FolderPath = Environment.getExternalStorageDirectory().getPath() + "/MyAppFolder";
private void setGridAdapter(String path) {
// Create a new grid adapter
gridItems = createGridItems(path);
MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
// Set the grid adapter
GridView gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(adapter);
// Set the onClickListener
gridView.setOnItemClickListener(this);
}
private List<GridViewItem> createGridItems(String directoryPath) {
List<GridViewItem> items = new ArrayList<GridViewItem>();
// List all the items within the folder.
files = new File(directoryPath).listFiles(new ImageFileFilter());
for (File file : files) {
// Add the directories containing images or sub-directories
if (file.isDirectory()
&& file.listFiles(new ImageFileFilter()).length > 0) {
items.add(new GridViewItem(file.getAbsolutePath(), true, null));
}
// Add the images
else {
Bitmap image = BitmapHelper.decodeBitmapFromFile(file.getAbsolutePath(),
50,
50);
items.add(new GridViewItem(file.getAbsolutePath(), false, image));
}
}
return items;
}
private boolean isImageFile(String filePath) {
if (filePath.endsWith(".jpg") || filePath.endsWith(".png") || filePath.endsWith(".pdf"))
// Add other formats as desired
{
return true;
}
return false;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (gridItems.get(position).isDirectory()) {
setGridAdapter(gridItems.get(position).getPath());
}
else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"),SELECT_PICTURE);
Log.e("Path for clicked Item::",gridItems.get(position).getPath());
}
}
private class ImageFileFilter implements FileFilter {
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
else if (isImageFile(file.getAbsolutePath())) {
return true;
}
return false;
}
}
我尝试过使用intent和onActivityResult方法但没有成功。这是我在设置gridview并在我的应用程序中显示文件夹时所遵循的solution。你能指导我在onClick Listener上做什么,以便直接在我的布局中打开图像。我不想通过画廊和展示图像。