如何在安卓中将文件名设置为文本视图



嗨,在下面的代码中,我正在使用一个名为选择文件的按钮。如果用户单击选择文件按钮,则显示三个选项,例如拍照,图库,取消。假设单击拍照打开相机并拍照,然后想要将图像名称设置为我的文本视图。

相同的功能也希望适用于图库。

例: 如果我从相机图像名称abc拍摄照片.jpeg 库也映像名称

谁能帮我?

public class OpportunityCreateFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the borderdashboard for this fragment
View rootView = inflater.inflate(R.layout.opportunity_form, container, false);
Textview no_file_pan=rootview.findViewById(R.id.no_file_pan);
pan_card.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectImage();
}
});


private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Gallery",
"Cancel"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
requestStoragePermission(true);
} else if (items[item].equals("Choose from Gallery")) {
requestStoragePermission(false);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}

/**
* Capture image from camera
*/
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = GenericFileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", photoFile);

mPhotoFile = photoFile;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);

}
}
}


/**
* Select image fro gallery
*/
private void dispatchGalleryIntent() {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickPhoto.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(pickPhoto, REQUEST_GALLERY_PHOTO);
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO) {
try {
mPhotoFile = mCompressor.compressToFile(mPhotoFile);
no_file_pan.setText(mPhotoFile.getAbsolutePath().substring(mPhotoFile.getAbsolutePath().lastIndexOf("/")+1));
} catch (IOException e) {
e.printStackTrace();
}
// Glide.with(getActivity()).load(mPhotoFile).apply(new RequestOptions().centerCrop().circleCrop().placeholder(R.drawable.profile_pic_place_holder)).into(profile);
} else if (requestCode == REQUEST_GALLERY_PHOTO) {
Uri selectedImage = data.getData();
try {
mPhotoFile = mCompressor.compressToFile(new File(getRealPathFromUri(selectedImage)));
no_file_pan.setText(mPhotoFile.getAbsolutePath().substring(mPhotoFile.getAbsolutePath().lastIndexOf("/")+1));
} catch (IOException e) {
e.printStackTrace();
}
//Glide.with(getApplicationContext()).load(mPhotoFile).apply(new RequestOptions().centerCrop().circleCrop().placeholder(R.drawable.profile_pic_place_holder)).into(profile);
}
}
}

/**
* Requesting multiple permissions (storage and camera) at once
* This uses multiple permission model from dexter
* On permanent denial opens settings dialog
*/
private void requestStoragePermission(final boolean isCamera) {
Dexter.withActivity((Activity) getContext()).withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
.withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
if (isCamera) {
dispatchTakePictureIntent();
} else {
dispatchGalleryIntent();
}
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
showSettingsDialog();
}
}

@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).withErrorListener(new PermissionRequestErrorListener() {
@Override
public void onError(DexterError error) {
Toast.makeText(getActivity().getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}


/**
* Showing Alert Dialog with Settings option
* Navigates user to app settings
* NOTE: Keep proper title and message depending on your app
*/
private void showSettingsDialog() {
android.app.AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Need Permissions");
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
openSettings();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();

}

// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getContext().getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}

/**
* Create file with current timestamp name
*
* @return
* @throws IOException
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String mFileName = "PAN"+"_";
File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File mFile = File.createTempFile(mFileName, ".jpg", storageDir);
return mFile;
}

/**
* Get real file path from URI
*
* @param contentUri
* @return
*/
public String getRealPathFromUri(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = getContext().getContentResolver().query(contentUri, proj, null, null, null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
return rootView;
}

使用此方法:

public String getFileName(File file) {
if (file == null) return "";
String fileName = "";
String path = file.getAbsolutePath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}

并像这样打电话:

no_file_pan.setText(getFileName(mPhotoFile));

试试这个

no_file_pan.setText(mPhotoFile.getAbsolutePath().substring(mPhotoFile.getAbsolutePath().lastIndexOf("/")+1));

使用这个有用的库从图库中选择图像并从相机 https://github.com/esafirm/android-image-picker 中拍照

:-

从中删除此no_file_pan.setText(mPhotoFile.getName());dispatchTakePictureIntent()这样的方法

/**
* Capture image from camera
*/
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
ex.printStackTrace();
// Error occurred while creating the File
}
if (photoFile != null) {
Uri photoURI = GenericFileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", photoFile);
mPhotoFile = photoFile;
// no_file_pan.setText(mPhotoFile.getName()); //remove or comment this line because file has not been created yet, better to set text in onActivity result
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}

最新更新