我想让用户拍下手机照片或从照片库中获取照片并将其添加到recyclerView列表中,每当他拍照时,回收者列表会自动增加,如果我从现在可以获得照片的话我想从相机或画廊获取它。 如何实现它谢谢
public void dialogShowPhoto() {
String takephoto = getString(R.string.take_photo);
String chooseFromLibrary = getString(R.string.choose_from_library);
String cancel = "cancel";
String addPhoto = "add photo";
final CharSequence[] items = {takephoto, chooseFromLibrary, cancel};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle(addPhoto);
final String finalTakephoto = takephoto;
final String finalChooseFromLibrary = chooseFromLibrary;
final String finalCancel = cancel;
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(finalTakephoto)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals(finalChooseFromLibrary)) {
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
} else if (items[item].equals(finalCancel)) {
dialog.dismiss();
}
}
});
builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA && resultCode == Activity.RESULT_OK) {
selectedImageWork.setAlpha(1f);
Bitmap photo = (Bitmap) data.getExtras().get("data");
// selectedImage.setImageBitmap(photo);
Matrix mat = new Matrix();
mat.postRotate(Integer.parseInt("270"));
Bitmap bMapRotate = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), mat, true);
selectedImageWork.setImageBitmap(bMapRotate);
}
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImageURI = data.getData();
PlaceWorkModel placeWorkModel = new PlaceWorkModel(); // the model between activity and adapter
placeWorkModel.setPhoto(Integer.parseInt(convertImage2Base64())); // here i pass the photo
picturesList.add(placeWorkModel);
mAdapter.notifyDataSetChanged();
}
}
// this method will convert the image to base64
public String convertImage2Base64() {
Bitmap bitmap = ((BitmapDrawable) selectedImageWork.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image = stream.toByteArray();
return ("data:image/jpeg;base64," + Base64.encodeToString(image, 0));
}
模型类
public class PlaceWorkModel {
private int photo;
public PlaceWorkModel(int photo) {
this.photo = photo;
}
public PlaceWorkModel() {
}
public int getPhoto() {
return photo;
}
public void setPhoto(int photo) {
this.photo = photo;
}
适配器
private Context mContext;
private List<PlaceWorkModel> picturesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
private ImageView picture;
public MyViewHolder(View view) {
super(view);
picture = (ImageView) view.findViewById(R.id.PlaceWorkRecycler_imageview_Picture);
}
}
public PlaceWorkRecyclerAdapter(Context mContext, ArrayList<PlaceWorkModel> picturesList) {
this.mContext = mContext;
this.picturesList = picturesList;
}
@Override
public PlaceWorkRecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.placework_recycler_adapterlayout, parent, false);
return new PlaceWorkRecyclerAdapter.MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final PlaceWorkRecyclerAdapter.MyViewHolder holder, int position) {
PlaceWorkModel listOfPictures = picturesList.get(position);
// loading picturesList using Glide library
Glide.with(mContext).load(listOfPictures.getPhoto())
.into(holder.picture);
}
@Override
public int getItemCount() {
return picturesList.size();
}
这是错误LogCat
12-16 17:50:47.630 11450-11476/com.foodservices.index.foodservices E/FA: Failed to send current screen to service
12-16 17:50:47.636 11450-11476/com.foodservices.index.foodservices E/FA: Discarding data. Failed to send event to service
12-16 17:50:49.317 11450-11450/com.foodservices.index.foodservices E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.foodservices.index.foodservices, PID: 11450
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/62/ORIGINAL/NONE/681675800 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F62/ORIGINAL/NONE/681675800} }} to activity {com.foodservices.index.foodservices/com.index.foodServices.common.view.activities.PlaceWorkActivity}: java.lang.ClassCastException: android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
at android.app.ActivityThread.deliverResults(ActivityThread.java:4268)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4312)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1644)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.ClassCastException: android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
at com.index.foodServices.common.view.activities.PlaceWorkActivity.convertImage2Base64(PlaceWorkActivity.java:196)
at com.index.foodServices.common.view.activities.PlaceWorkActivity.onActivityResult(PlaceWorkActivity.java:184)
at android.app.Activity.dispatchActivityResult(Activity.java:7267)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4264)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4312)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1644)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
答案 0 :(得分:1)
您没有将更新的列表设置为适配器。
在适配器中添加功能更新
public void updateList(List<PlaceWorkModel> picturesList) {
this.picturesList = picturesList;
notifyDataSetChanged();
}
然后,
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImageURI = data.getData();
PlaceWorkModel placeWorkModel = new PlaceWorkModel(); // the model between activity and adapter
placeWorkModel.setPhoto(Integer.parseInt(convertImage2Base64())); // here i pass the photo
picturesList.add(placeWorkModel);
mAdapter.updateList(picturesList); // add this
mAdapter.notifyDataSetChanged();
}
答案 1 :(得分:0)
也许easyImage库会帮助你
以下是一个如何使用该库以便从设备拍摄照片并将其保存到您的应用中的示例,之后您可以将其设置为您的视图
private void OpenImage() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Options");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (items[i].equals("Camera")) {
EasyImage.openCamera(EditorActivity.this, REQUEST_CODE_CAMERA);
} else if (items[i].equals("Gallery")) {
EasyImage.openGallery(EditorActivity.this, REQUEST_CODE_GALLERY);
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
@Override
public void onImagePicked(File imageFile, EasyImage.ImageSource source, int type) {
switch (type) {
case REQUEST_CODE_CAMERA:
Glide.with(EditorActivity.this)
.load(imageFile)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(img);
saveImage(imageFile.getAbsolutePath());
break;
case REQUEST_CODE_GALLERY:
Glide.with(EditorActivity.this)
.load(imageFile)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(img);
saveImage(imageFile.getAbsolutePath());
break;
}
}
});
}
private void saveImage(String imagePath) {
pictureChanged = true;
try {
FileInputStream file = new FileInputStream(imagePath);
byte[] image = new byte[file.available()];
file.read(image);
} catch (IOException e) {
e.printStackTrace();
}
}
答案 2 :(得分:0)
我认为问题在于您的 convertImage2Base64 尝试将其更改为如下所示
public byte[] convertImage2Base64() {
Bitmap bitmap = ((BitmapDrawable) selectedImageWork.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image = Base64.decode(stream.toByteArray(), Base64.DEFAULT);
return image;
}
并对您的模型进行如下更改。
public class PlaceWorkModel {
private byte[] photo;
public PlaceWorkModel(byte[] photo) {
this.photo = photo;
}
public PlaceWorkModel() {
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
我假设你能够在片段/活动中调用函数并从图库或摄像头获取图像,唯一的问题是没有加载图像的滑动。试试这个,让我知道它是否有效。