2016-05-10 8 views
0

私のアンドロイドアプリケーションに表示されるカードに共有機能を提供しようとしています。私はShareactionProviderについて知っている。このactionProviderはすべてのカードビューに存在すると想定されます。私はShareActionproviderのコードをアダプタのonBindViewHolderに配置しました。アプリが起動すると、すべてのカードが同時に共有を実行します。この共有は、ユーザーが要求したときにのみ呼び出すことにします。RecyclerviewのCardViewでShareActionProviderを使用する

@Override 
public void onBindViewHolder(final ViewHolder viewHolder, final Cursor cursor) { 
final NewsFacade facade = NewsFacade.fromCursor(cursor); 
MenuItem shareMenuItem = viewHolder.toolbar.getMenu().findItem(R.id.share); 
    ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareMenuItem); 
    shareActionProvider.setShareIntent(viewHolder.sendShareIntent(facade, context)); 
    shareActionProvider.setShareHistoryFileName("custom_share_history.xml"); 

そして、ここでの共有を支援するヘルパーメソッドです:

public Intent sendShareIntent(NewsFacade facade, Context context) 
    { 
     saveImageToCache(facade, context); 
     return shareImage(context); 
    } 

    private void saveImageToCache(NewsFacade facade, Context context) 
    { 
     try { 
      Bitmap bitmap = facade.getThumb(); 
      File cachePath = new File(context.getCacheDir(), "images"); 
      cachePath.mkdirs(); 
      FileOutputStream stream = new FileOutputStream(cachePath + "/image.png"); // overwrites this image every time 
      bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 
      stream.close(); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    private Intent shareImage(Context context) 
    { 
     File imagePath = new File(context.getCacheDir(), "images"); 
     File newFile = new File(imagePath, "image.png"); 
     Uri contentUri = FileProvider.getUriForFile(context, "com.example.clinton.companion.fileprovider", newFile); 

     if (contentUri != null) { 

      Intent shareIntent = new Intent(); 
      shareIntent.setAction(Intent.ACTION_SEND); 
      shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file 
      shareIntent.setDataAndType(contentUri,context.getContentResolver().getType(contentUri)); 
      shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri); 
      context.startActivity(Intent.createChooser(shareIntent, "Choose an app")); 
      return shareIntent; 

     } 
     return null; 
    } 

私が知っている、私は間違った場所にActionProviderを呼び出しています。しかし、どこでこれを呼び出す必要がありますか、私はカードビューが保持するオブジェクトのインスタンスが必要なので、私は共有するために、cardviewでイメージを得ることができます。

ご了承ください。

答えて

0

私はそれを修正しました。 私は自動的に共有を実行

context.startActivity(Intent.createChooser(shareIntent, "Choose an app")); 

を呼んでいました。

関連する問題