如何打开库以在特定目录中显示图像

时间:2011-11-24 07:06:38

标签: android directory gallery

  

可能重复:
  Gallery with folder filter

我的应用在sdcard目录中创建图片,我想为它打开图库。要做到这一点,我只需遵循:

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    startActivity(intent);  

但它会显示设备中的每张照片。是否可以只显示目录中的文件?

1 个答案:

答案 0 :(得分:2)

你只需要在你的活动中实现MediaScannerConnectionClient,之后你必须在这个文件夹名称中给出一个文件的确切路径作为SCAN_PATH,它将扫描包含在该文件夹中的所有文件并在内置中打开它在画廊。所以只要给出你文件夹的名称,你就会得到包括视频在内的所有文件。如果您只想打开图片,请更改FILE_TYPE="images/*"

public class sdActivity extends Activity implements MediaScannerConnectionClient{
    public String[] allFiles;
private String SCAN_PATH ;
private static final String FILE_TYPE = "*/*";

private MediaScannerConnection conn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    File folder = new File("/sdcard/youfoldername/");
    allFiles = folder.list();
 //   uriAllFiles= new Uri[allFiles.length];
    for(int i=0;i<allFiles.length;i++)
    {
        Log.d("all file path"+i, allFiles[i]+allFiles.length);
    }
  //  Uri uri= Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0]));
    SCAN_PATH=Environment.getExternalStorageDirectory().toString()+"/yourfoldername/"+allFiles[0];
    Log.d("SCAN PATH", "Scan Path " + SCAN_PATH);
    Button scanBtn = (Button)findViewById(R.id.scanBtn);
    scanBtn.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        startScan();
    }});
    }
    private void startScan()
    {
    Log.d("Connected","success"+conn);
    if(conn!=null)
    {
    conn.disconnect();
    }
    conn = new MediaScannerConnection(this,this);
    conn.connect();
    }
@Override
public void onMediaScannerConnected() {
    Log.d("onMediaScannerConnected","success"+conn);
    conn.scanFile(SCAN_PATH, FILE_TYPE);    
}
@Override
public void onScanCompleted(String path, Uri uri) {
    try {
        Log.d("onScanCompleted",uri + "success"+conn);
        if (uri != null) 
        {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(uri);
        startActivity(intent);
        }
        } finally 
        {
        conn.disconnect();
        conn = null;
        }
       }
}

我已经在此链接上回复了Built-in gallery in specific folder