2017-02-21 19 views
1

У меня есть recyclerView, который загружает изображения из firebase, используя picasso. Каждый элемент (изображение) имеет под ним элемент shareButton, который при нажатии преобразует представление в растровое изображение и использует намерение поделиться им с другим Программы. Проблема в том, что он разделяет следующий образ (элемент), а не изображение, под которым размещался shareButton. Вот код для преобразования растровых изображений и share-Viewholder onClickListener ссылается на неверный вид в android

// Can be triggered by a view event such as a button press 
public void onShareItem(View v) { 
    // Get access to bitmap image from view 
    ImageView ivImage = (ImageView) findViewById(R.id.post_image); 
    // Get access to the URI for the bitmap 
    Uri bmpUri = getLocalBitmapUri(ivImage); 
    if (bmpUri != null) { 
     // Construct a ShareIntent with link to image 
     Intent shareIntent = new Intent(); 
     shareIntent.setAction(Intent.ACTION_SEND); 
     shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri); 
     shareIntent.setType("image/*"); 

     // Launch sharing dialog for image 
     startActivity(Intent.createChooser(shareIntent, "Share Image")); 

    } else { 

    } 
} 

// Returns the URI path to the Bitmap displayed in specified ImageView 
public Uri getLocalBitmapUri(ImageView imageView) { 
    // Extract Bitmap from ImageView drawable 
    Drawable drawable = imageView.getDrawable(); 
    Bitmap bmp = null; 
    if (drawable instanceof BitmapDrawable){ 
     bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); 
    } else { 
     return null; 
    } 
    // Store image to default external storage directory 
    Uri bmpUri = null; 
    try { 
     File file = new File(Environment.getExternalStoragePublicDirectory(
       Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png"); 
     file.getParentFile().mkdirs(); 
     FileOutputStream out = new FileOutputStream(file); 
     bmp.compress(Bitmap.CompressFormat.PNG, 90, out); 
     out.close(); 
     bmpUri = Uri.fromFile(file); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return bmpUri; 
} 

Как кнопка доля Setup-

 protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) { 
      viewHolder.setTitle(model.getTitle()); 

      viewHolder.setImage(getApplicationContext(), model.getImage()); 


      viewHolder.mShareButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 

        onShareItem(view); 



       } 
      }); 


     } 
    }; 

    mBlogList.setAdapter(firebaseRecyclerAdapter); 


} 

public static class BlogViewHolder extends RecyclerView.ViewHolder { 
    View mView; 

    Button mShareButton; 


    public BlogViewHolder(View itemView) { 
     super(itemView); 
     mView = itemView; 
     mShareButton = (Button) mView.findViewById(R.id.btn_share); 
    } 

Это, как я добавляю данные

public static class BlogViewHolder extends RecyclerView.ViewHolder { 
    View mView; 

    Button mShareButton; 


    public BlogViewHolder(View itemView) { 
     super(itemView); 
     mView = itemView; 
     mShareButton = (Button) mView.findViewById(R.id.btn_share); 
    } 


    public void setTitle(String title) { 
     TextView post_title = (TextView) mView.findViewById(R.id.post_title); 
     post_title.setText(title); 
    } 

    public void setImage(final Context ctx, final String image) { 


     final ImageView post_image = (ImageView) mView.findViewById(R.id.post_image); 


     Picasso.with(ctx) 
       .load(image) 
       .networkPolicy(NetworkPolicy.OFFLINE) 
       .into(post_image, new Callback() { 
        @Override 
        public void onSuccess() { 


        } 

        @Override 
        public void onError() { 
         Picasso.with(ctx) 
           .load(image) 
           .error(R.drawable.header) 
           .placeholder(R.drawable.progress_animation) 
           .into(post_image); 
        } 


       }); 


    } 


} 

}

+0

Я не уверен, почему вы делаете 'ImageView ivImage = (ImageView) findViewById (R.id.post_image)' вместо 'ImageView ivImage = (ImageView) v,' в 'onShareItem' метод. – Titus

+1

@Titus Я попробовал, но получил следующую ошибку, когда я нажимаю кнопку совместного доступа. java.lang.ClassCastException: android.support.v7.widget.AppCompatButton нельзя отнести к android.widget.ImageView –

+0

О, теперь я вижу, что вы передаете 'Button' методу' onShareItem', вам понадобятся вместо этого передать его «ImageView». – Titus

ответ

0

Почему бы просто не передать изображение самому методу долей?

protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) { 
      viewHolder.setTitle(model.getTitle()); 
      viewHolder.setImage(getApplicationContext(), model.getImage()); 
      viewHolder.mShareButton.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        onShareItem(model.getImage()); 
       } 
      }); 
     } 

Затем отправьте изображение uri напрямую.

// Can be triggered by a view event such as a button press 
public void onShareItem(String image) { 
     Uri imageUri = Uri.parse(image); 

     // Construct a ShareIntent with link to image 
     Intent shareIntent = new Intent(); 
     shareIntent.setAction(Intent.ACTION_SEND); 
     shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri); 
     shareIntent.setType("image/*"); 

     // Launch sharing dialog for image 
     startActivity(Intent.createChooser(shareIntent, "Share Image")); 
} 
+1

Это не сработало «Ошибка формата файла» в каждом приложении. Думаю, нам нужно сначала преобразовать изображение в растровое изображение. Теперь я буквально устал от этой ошибки. @ Scott –