0

我正在创建联系人应用程序。创建新联系人时,用户可以打开相机并拍照。有一个使用ContactsActivity显示所有Contacts 的RecyclerView。在RecyclerView(ContactsAdapter) 内部,我正在重新计算拍摄图像的大小,并将缩放ImageView后的图像放入RecyclerView.

在相当长的一段时间内,我得到ArithmeticException, sincegetWidth()并且getHeight()返回 0。我通过使用ViewTreeObserver.

我有一个辅助方法 ( PictureUtils.getScaledBitmap()) 可以调整拍摄照片的大小。为了清楚起见,我没有在这里展示它。

我面临的核心问题是,当我创建两个Contacts 并移至 时ContactsActivity,我看到了这两个Contacts,但每个Contact都拍摄了第一张照片!

Contact班级:

    public class Contact {

    private int id, mAvatar;
    private String mFirstname;
    private String mLastname;
    private String mEmail;
    private String mCurrentPhotoPath;
}

这就是我onBindViewHolder()在 RecyclerView 中的内容:

    @Override
    public void onBindViewHolder(ViewHolder holder, int position){
        //Set the values inside the given view
        CardView cardView = holder.cardView;
        currentContact = mContacts.get(position); //mContacts is collection passed to the constructor of RecyclerView

        ImageView imageView = (ImageView)cardView.findViewById(R.id.image_profile);


        ViewTreeObserver observer = imageView.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {

                if (currentContact.getCurrentPhotoPath() != null) {
                    Log.i("WIDTH",String.valueOf(imageView.getWidth())); //Here I get desired value
                    Log.i("HEIGHT",String.valueOf(imageView.getHeight())); //Here as well
                    Log.i("Photo path: ", currentContact.getCurrentPhotoPath()); //Here, I get path/IMG_0, for both images, I need to get path/IMG_0 and path/IMG_1

                    Bitmap bitmap = PictureUtils.getScaledBitmap(currentContact.getCurrentPhotoPath(), width, height);

                    imageView.setImageBitmap(bitmap);


                } else {
                    if (currentContact.getAvatar() != 0){
                        Drawable drawable = cardView.getResources().getDrawable(mContacts.get(position).getAvatar());
                        imageView.setImageDrawable(drawable);
                    }
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            }
        });
}

如何为每张Contact照片显示?

编辑(对于下面的评论者)

这是 ViewHolder,它包含在 RecyclerView 中:

 public static class ViewHolder extends RecyclerView.ViewHolder {

    private CardView cardView;
    private LinearLayout mLinearLayout;

    public ViewHolder(CardView v) {
        super(v);
        cardView = v;
        mLinearLayout = cardView.findViewById(R.id.linear_layout);
    }

}
4

0 回答 0