我有一个屏幕,当有人单击按钮时会出现一个AlertDialog,用户可以选择拍照或从图库中选择。 Gallery的代码运行良好,但另一个代码却无效。这个想法是拍一张照片并在recyclerview中显示。在下面,我将发布代码:
public class NovoConteudoActivity extends AppCompatActivity{
private RecyclerView recyclerViewAddImage;
private ImageButton buttonAddNewImage;
private List<Imagem> listImagens = new ArrayList<>();
private AdapterImagem adapter;
private Imagem imagemConfigurada;
private ImageView imageDimension;
String currentImagePath = null;
private String[] permissoesNecessarias = new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
};
private static final int SELECAO_CAMERA = 100;
private static final int SELECAO_GALERIA = 200;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_novo_conteudo);
//Inicializar Componentes:
inicalizarComponentes();
//Validar Permissões:
Permissao.validarPermissoes(permissoesNecessarias, this, 1);
//Set Adapter:
adapter = new AdapterImagem(listImagens, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
layoutManager.setStackFromEnd(true);
recyclerViewAddImage.setLayoutManager(layoutManager);
recyclerViewAddImage.setHasFixedSize(true);
recyclerViewAddImage.setAdapter(adapter);
//Evento de clique no Botão para adicionar imagem:
buttonAddNewImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
criarAlertDialog();
}
});
}
@Override
protected void onStart() {
super.onStart();
recyclerViewAddImage.smoothScrollToPosition(listImagens.size());
if (listImagens.size() >= 6){
buttonAddNewImage.setVisibility(View.GONE);
}else {
buttonAddNewImage.setVisibility(View.VISIBLE);
}
}
private void inicalizarComponentes() {
recyclerViewAddImage = findViewById(R.id.recyclerViewAddImage);
buttonAddNewImage = findViewById(R.id.buttonAddNewImage);
imageDimension = findViewById(R.id.imageDimension);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public void criarAlertDialog(){
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Escolha uma opção");
alertDialog.setCancelable(true);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
LinearLayout linearLayoutVertical = new LinearLayout(this);
linearLayoutVertical.setOrientation(LinearLayout.VERTICAL);
linearLayoutVertical.setLayoutParams(params);
TextView textCamera = new TextView(this);
textCamera.setText("Tirar foto");
textCamera.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_photo_camera_black_24dp, 0,0,0);
textCamera.setCompoundDrawablePadding(5);
textCamera.setGravity(Gravity.CENTER_VERTICAL);
textCamera.setLayoutParams(params);
textCamera.setPadding(16,16,10,16);
linearLayoutVertical.addView(textCamera);
TextView textGaleria = new TextView(this);
textGaleria.setText("Escolher Existente...");
textGaleria.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_photo_black_24dp, 0,0,0);
textGaleria.setCompoundDrawablePadding(5);
textGaleria.setGravity(Gravity.CENTER_VERTICAL);
textGaleria.setLayoutParams(params);
textGaleria.setPadding(16,10,10,16);
linearLayoutVertical.addView(textGaleria);
TextView textCancelar = new TextView(this);
textCancelar.setText("Cancelar");
textCancelar.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_close_cinza_24dp, 0,0,0);
textCancelar.setCompoundDrawablePadding(5);
textCancelar.setGravity(Gravity.CENTER_VERTICAL);
textCancelar.setLayoutParams(params);
textCancelar.setPadding(16,10,10,16);
linearLayoutVertical.addView(textCancelar);
alertDialog.setView(linearLayoutVertical);
final AlertDialog dialog = alertDialog.create();
dialog.show();
textCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (i.resolveActivity(getPackageManager()) != null){
File imageFile = null;
try {
imageFile = getImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (imageFile != null){
Uri imageUri = FileProvider.getUriForFile(NovoConteudoActivity.this,
"com.gustavo.android.fileprovider",
imageFile);
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(i, SELECAO_CAMERA);
}
}
dialog.dismiss();
}
});
textGaleria.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
if (i.resolveActivity(getPackageManager()) != null){
startActivityForResult(i, SELECAO_GALERIA);
}
dialog.dismiss();
}
});
textCancelar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
Bitmap imagem = null;
try {
switch (requestCode){
case SELECAO_CAMERA:
rotateImage(setReducedImageSize());
break;
case SELECAO_GALERIA:
Uri localImagemSelecionada = data.getData();
InputStream imageStream = getContentResolver().openInputStream(localImagemSelecionada);
imagem = BitmapFactory.decodeStream(imageStream);
if (imagem!= null){
imagemConfigurada = new Imagem();
imagemConfigurada.setImagem(imagem);
listImagens.add(imagemConfigurada);
Log.d("Imagem", "onActivityResult: " + listImagens);
adapter.notifyDataSetChanged();
}
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
}
private File getImageFile()throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
currentImagePath = image.getAbsolutePath();
return image;
}
private Bitmap setReducedImageSize(){
int targetImageViewWidth = imageDimension.getWidth();
int targetImageViewHeight = imageDimension.getHeight();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(currentImagePath, bmOptions);
int cameraImageWidth = bmOptions.outWidth;
int cameraImageHeight = bmOptions.outHeight;
int scaleFactor = Math.min(cameraImageWidth/targetImageViewWidth, cameraImageHeight/targetImageViewHeight);
bmOptions.inSampleSize = scaleFactor;
bmOptions.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(currentImagePath, bmOptions);
}
private void rotateImage(Bitmap bitmap){
ExifInterface exifInterface = null;
try {
exifInterface = new ExifInterface(currentImagePath);
}catch (IOException e){
e.printStackTrace();
}
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
Matrix matrix = new Matrix();
switch (orientation){
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(270);
break;
default:
}
Bitmap imageRotate = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
if (imageRotate!= null){
imagemConfigurada = new Imagem();
imagemConfigurada.setImagem(imageRotate);
listImagens.add(imagemConfigurada);
Log.d("Lista", "rotateImage: " + listImagens);
adapter.notifyDataSetChanged();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int permissaoResultado: grantResults){
if (permissaoResultado == PackageManager.PERMISSION_DENIED){
alertaValidacaoPermissao();
}
}
}
private void alertaValidacaoPermissao(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Permissões Negadas");
builder.setMessage("Para utilizar o app é necessário aceitar as permissões");
builder.setCancelable(false);
builder.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
使用适配器代码:
public class AdapterImagem extends RecyclerView.Adapter<AdapterImagem.MyViewHolder> {
List <Imagem> list;
Context context;
public AdapterImagem(List<Imagem> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View item = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_add_photo, parent, false);
return new AdapterImagem.MyViewHolder(item);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Imagem imagem = list.get(position);
Glide
.with(context)
.load(imagem.getImagem())
.centerCrop()
.into(holder.newImagem);
}
@Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView newImagem;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
newImagem = itemView.findViewById(R.id.newImage);
}
}
}
和类Imagem:
public class Imagem {
private Bitmap imagem;
public Imagem() {
}
public Imagem(Bitmap imagem) {
this.imagem = imagem;
}
public Bitmap getImagem() {
return imagem;
}
public void setImagem(Bitmap imagem) {
this.imagem = imagem;
}
}
//don't initialize here
adapter = new AdapterImagem(listImagens, this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
.........
而不是在这里初始化:
case SELECAO_GALERIA:
Uri localImagemSelecionada = data.getData();
InputStream imageStream = getContentResolver().openInputStream(localImagemSelecionada);
imagem = BitmapFactory.decodeStream(imageStream);
if (imagem!= null){
imagemConfigurada = new Imagem();
imagemConfigurada.setImagem(imagem);
listImagens.add(imagemConfigurada);
//here
adapter = new AdapterImagem(listImagens, this);
Log.d("Imagem", "onActivityResult: " + listImagens);
adapter.notifyDataSetChanged();
}
break;