我是Android应用程序开发的新手。我有一个简单的问题。我用Google搜索,但无法找到任何满意的答案。我的问题是:
我们可以使用startactivityforresult()方法将图像复制并移动到另一个文件夹。如果是,那么我们如何传递我们想要移动或复制的所选图像的位置?
由于
答案 0 :(得分:1)
在您的主要活动中:
创建新的ArrayList以保存所选图像:
ArrayList<Model_images> selectedImages = new ArrayList<Model_Images>();
将所有选定的图像添加到适配器中的selectedImages
onClick使用:
selectedImages.add(al_images.get(position));
然后,如果您拥有所选图像的列表,请构建意图和 打电话给活动:
Intent moveIntent = new Intent(this, MoveActivity.class);
moveIntent.putExtra("selected_images", selectedImages);
startActivityForResult(moveIntent, REQUEST_CODE); // REQUEST_CODE is a unique int value within your app for this intent.
覆盖onActivityResult
以接收回复:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed(REQUEST_CODE)
if(requestCode==REQUEST_CODE)
{
if (resultCode == RESULT_OK){
//The called activity completed successfully.
String message=data.getStringExtra("MESSAGE"); //The message passed along with result
}
}
}
在MoveActivity
活动中:
获取传递的ArrayList:
ArrayList<model_Images> selectedImages = new ArrayList<Model_Images>();
if(getIntent().getSerializableExtra("selected_images") != null)
selectedImages = getIntent().getSerializableExtra("selected_images");
将图像移动到目标文件夹:
//Move each selected file to destination
for (Model_Images image : selectedImages{
File sourceImage = image.getFile(); //returns the image File from model class to be moved.
File destinationImage = new File("path/to/destination", "filename.extension");
moveFile(sourceImage, destinationImage);
}
//Method to move the file
private void moveFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
source.delete();
}
完成后将结果设置为调用活动:
// Set result back to the calling activity
Intent intent=new Intent();
intent.putExtra("MESSAGE",message); // Set a message for the calling activity
setResult(RESULT_OK,intent); //RESULT_OK represents success result
finish();//finishing activity
P.S:不讨论处理存储权限,需要读/写。