如何使用内置图库android打开图像文件?

时间:2013-01-18 07:28:39

标签: android

您好我想在Android中使用内置图库打开图片。现在我使用以下代码,如果我单击按钮,它会显示包含安装的第三方工具以打开图像的菜单。我只想要内置图库,是否有任何隐藏其他第三方工具的选项我可以直接使用图库打开而不显示菜单。

package com.example.gallery;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BrowsePicture extends Activity {

private static final int SELECT_PICTURE = 1;
Button bt;
private String selectedImagePath;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_browse_picture);

    bt = (Button) findViewById(R.id.button1);
            bt.setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {

                    // in onCreate or any event where your want the user to
                    // select a file
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(
                            Intent.createChooser(intent, "Select Picture"),
                            SELECT_PICTURE);
                }
            });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
        }
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

}

2 个答案:

答案 0 :(得分:6)

尝试使用

Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, SELECT_PICTURE);

答案 1 :(得分:1)

这是因为点击按钮后,您传递的意图是设置其类型intent.setType("image/*");intent.setAction(Intent.ACTION_GET_CONTENT);,以便显示设备上安装的应用列表。

如果您只想直接打开图库,那么您应该只为图库传递意图。