所以我发现了一个提示用户打开设备库的功能。但在搜索时我找不到任何可以帮助我修改它以返回图像路径的东西。他们说onActivityResult(),我把它放在虚空本身,然后被拒绝。对此有何帮助?
public void chooser() {
AlertDialog.Builder myDialog
= new AlertDialog.Builder(IPAddress.this);
myDialog.setTitle("Import Menu Images");
LinearLayout layout = new LinearLayout(IPAddress.this);
layout.setOrientation(LinearLayout.VERTICAL);
myDialog.setView(layout);
myDialog.setPositiveButton("Open Folder", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
}
});
myDialog.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
});
myDialog.show();
}
我希望它返回所选图像的路径,然后我将使用该路径复制所述文件并将其保存到我在活动的OnCreate上创建的目录中。
另外,我似乎无法调试上述功能,因为当我点击“打开文件夹”按钮时,会出错提示
The application Camera(process.com.android.gallery) has stopped unexpectedly. Please try again.
我多次尝试过。我甚至在模拟器中添加了一个前置摄像头。
此处调用该函数:
Button menu_image = (Button) findViewById(R.id.menu_image);
menu_image.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
chooser();
}
});
所以我希望选择器返回一个字符串(?)类型,如果可能的话,我将用它来复制文件,然后重命名。
答案 0 :(得分:1)
可以通过以下方式查询默认的应用选择器。
Button galleryBtn = (Button) view.findViewById(R.id.gallery_btn);
galleryBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"), 2);
}
});
您将在活动/片段的onActivityResult()中收到所选文件的URi。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uriString = null;
if (requestCode == 2 && resultCode == RESULT_OK) {
Uri uri = data.getData();
if (uri != null) {
Cursor cursor = getActivity().getContentResolver()
.query(uri,
new String[] { android.provider.MediaStore.Images.ImageColumns.DATA },
null, null, null);
cursor.moveToFirst();
Bitmap bm = BitmapFactory.decodeFile(cursor.getString(0));
File file = new File(cursor.getString(0));
uriString = Uri.fromFile(file);
// do processing with the uri here
cursor.close();
}
}else{
Log.e("RDT", "Something went wrong.");
return;
}
}