Search code examples
androidandroid-viewpager

OnClick listener on Viewpager is triggered on the wrong reference


I have a ViewPager in my MainActivity and i am loading contents into it, which is working completely fine, but when i am setting onClickListener on the button to take the screenshot of that particular page, the screenshot is getting captured but of the next page, i have done debugging of the code but i am not able to find the exact reason for this. Here i am attaching the codes for the reference. Can somebody check where i am doing wrong?

I have tried searching the issue on this platform but none of them seems to have the solution to my problem.

Adapter Code

public class ArticleAdapter extends PagerAdapter {

public List<Articles> articlesListChild;
private LayoutInflater inflater;
Context context;
View rootView;

public ArticleAdapter(Context context) {
    super();
    this.context = context;
}

@Override
public int getCount() {
    return articlesListChild.size();
}


@Override
public void destroyItem(View collection, int position, Object view) {
    ((ViewPager) collection).removeView((View) view);
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == object;
}

@SuppressLint("ClickableViewAccessibility")
@Override
public Object instantiateItem(ViewGroup container, final int position) {

    inflater = LayoutInflater.from(container.getContext());
    View viewLayout = inflater.inflate(R.layout.article_single_item, null, false);
    final ImageView contentIv, imageContentIv;
    TextView contentHeadTv, contentBodyTv,
      sharingTextTv;
    LinearLayout articleDetailsLl;
    final LinearLayout articlesPager, articleBookmarkBtn,
            articleBookmarkedBtn, articleShareBtn;

    contentIv = (ImageView) viewLayout.findViewById(R.id.content_iv);
    contentHeadTv = (TextView) viewLayout.findViewById(R.id.content_head_tv);
    contentBodyTv = (TextView) viewLayout.findViewById(R.id.content_body_tv);
    articlesPager = (LinearLayout) viewLayout.findViewById(R.id.article_pager);

    articlesLayout = (LinearLayout) viewLayout.findViewById(R.id.articles_layout);

    rootView = viewLayout.findViewById(R.id.post_main_cv);


    RequestOptions requestOptions = new RequestOptions();
       requestOptions.placeholder(R.drawable.placeholder);
       Glide.with(context)
          .setDefaultRequestOptions(requestOptions)       
          .load(articlesListChild.get(position).getArticleImage())
          .into(contentIv);
        toolbar.setVisibility(GONE);
        articlesPager.setVisibility(GONE);
        contentIv.setScaleType(ImageView.ScaleType.FIT_XY);
     contentHeadTv.setText(articlesListChild.get(position).getArticleHeading().trim());
        contentBodyTv.setText(articlesListChild.get(position).getArticleContent().trim());
        contentSourceTv.setText(articlesListChild.get(position).getArticleSource().trim());

 articleShareBtn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
       Bitmap screenshotBitmap = takeScreenshot();
       saveAndShareScreenshot(screenshotBitmap);
   }
 });

private Bitmap takeScreenshot() {
    rootView.setDrawingCacheEnabled(true);
    Bitmap screenshotBitmap = rootView.getDrawingCache();
    return screenshotBitmap;
}

private void saveAndShareScreenshot(Bitmap screenshotBitmap) {
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        // Save Screenshot
        File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/MyApp Screenshots");
        myDir.mkdir();
        String fname = "Image-" + 1 + ".jpg";
        File file = new File(myDir, fname);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
            FileOutputStream out = new FileOutputStream(file);
            screenshotBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        MediaScannerConnection.scanFile(context, new String[]{file.toString()}, new String[]{file.getName()}, null);
        // Share Screenshot
        file.setReadable(true, false);
        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri photoURI = FileProvider.getUriForFile(context, "com.xyz.abcapp.provider", file);
        String shareBody = "Share"
        intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Read this article");
        intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        intent.putExtra(Intent.EXTRA_STREAM, photoURI);
        intent.setType("image/*");
        context.startActivity(Intent.createChooser(intent,"Share Using"));
    } else {
        Toast.makeText(context, "Permissions not granted", Toast.LENGTH_SHORT).show();
    }

}

single_item.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/tools"
android:id="@+id/post_main_rl"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.CardView
    android:id="@+id/post_main_cv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    card_view:cardUseCompatPadding="true">

    <!--Articles layout starts-->
    <LinearLayout
        android:id="@+id/articles_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="10">

        <ImageView
            android:id="@+id/content_iv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="false"
            android:fitsSystemWindows="false"
            android:layout_weight="5.5"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_weight="4.5">

            <TextView
                android:id="@+id/content_head_tv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/content_iv"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="10dp"
                android:fontFamily="@font/chivo_regular"
                android:gravity="center_vertical"
                android:lineSpacingExtra="1dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:text="This is a headg"
                android:textColor="#191919"
                android:textSize="@dimen/article_head" />

            <TextView
                android:id="@+id/content_body_tv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/content_head_tv"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="10dp"
                android:lineSpacingExtra="4dp"
                android:fontFamily="@font/chivo_light"
                android:paddingLeft="10dp"
                android:textColor="#6b6b6b"
                android:paddingRight="10dp"
                android:textSize="@dimen/article_body" />

        </LinearLayout>

     </LinearLayout>


    <!--Articles layout ends-->
    <!--Article Buttons-->
    <LinearLayout
        android:id="@+id/article_pager"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="bottom"
        android:background="@drawable/grad_2"
        android:orientation="horizontal"
        android:visibility="gone"
        android:weightSum="2">

        <LinearLayout
            android:id="@+id/article_bookmarked_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:orientation="vertical"
            android:padding="3dp"
            android:textAlignment="center"
            android:visibility="gone">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/nav_bookmarked_white" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="3dp"
                android:text="BOOKMARKED"
                android:textColor="@color/colorWhite"
                android:fontFamily="@font/chivo_regular"
                android:textSize="@dimen/article_btn_text" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/article_bookmark_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:orientation="vertical"
            android:padding="3dp">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center"
                android:src="@drawable/nav_bookmark_white" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical|center"
                android:padding="3dp"
                android:text="BOOKMARK"
                android:textColor="@color/colorWhite"
                android:fontFamily="@font/chivo_regular"
                android:textSize="@dimen/article_btn_text" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/article_share_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:orientation="vertical"
            android:padding="3dp"
            android:textAlignment="center">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/nav_share_white" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="3dp"
                android:text="SHARE"
                android:textColor="@color/colorWhite"
                android:fontFamily="@font/chivo_regular"
                android:textSize="@dimen/article_btn_text" />

        </LinearLayout>        
    </LinearLayout>
</android.support.v7.widget.CardView>

I am unable to take the screenshot of the current viewpager item.


Solution

  • As @MikeM. suggested in the comment

    Well, there are several different ways to do this. Assuming articleShareBtn is in each individual page, probably the simplest would be to articleShareBtn.setTag(rootView) after the rootView = ... line, then change your method to private Bitmap takeScreenshot(View root) { root.setDrawingCacheEnabled(true); ... }, and inside the onClick(), you would call it like Bitmap screenshotBitmap = takeScreenshot((View) view.getTag());. Follow me? Otherwise, you could keep a Map all the page Views, and use the current index to get the right one. There's a few other ways, too, if necessary.

    I got it working. My updated Adapter code is

    public class ArticleAdapter extends PagerAdapter {
    
       public List<Articles> articlesListChild;
       private LayoutInflater inflater;
       Context context;
       View rootView;
    
       public ArticleAdapter(Context context) {
          super();
          this.context = context;
       }
    
       @Override
       public int getCount() {
          return articlesListChild.size();
       }
    
    
       @Override
       public void destroyItem(View collection, int position, Object view) {
          ((ViewPager) collection).removeView((View) view);
       }
    
       @Override
       public boolean isViewFromObject(View view, Object object) {
          return view == object;
       }
    
    
       @SuppressLint("ClickableViewAccessibility")
       @Override
       public Object instantiateItem(ViewGroup container, final int position) {
          inflater = LayoutInflater.from(container.getContext());
          View viewLayout = inflater.inflate(R.layout.article_single_item, null, false);
          final ImageView contentIv, imageContentIv;
          TextView contentHeadTv, contentBodyTv, sharingTextTv;
          LinearLayout articleDetailsLl;
          final LinearLayout articlesPager, articleBookmarkBtn,
          articleBookmarkedBtn, articleShareBtn;
    
          contentIv = (ImageView) viewLayout.findViewById(R.id.content_iv);
          contentHeadTv = (TextView) viewLayout.findViewById(R.id.content_head_tv);
          contentBodyTv = (TextView) viewLayout.findViewById(R.id.content_body_tv);
          articlesPager = (LinearLayout) viewLayout.findViewById(R.id.article_pager);
    
          articlesLayout = (LinearLayout) viewLayout.findViewById(R.id.articles_layout);
    
          rootView = viewLayout.findViewById(R.id.post_main_cv);
        articleShareBtn.setTag(rootView);
    
    
          RequestOptions requestOptions = new RequestOptions();
          requestOptions.placeholder(R.drawable.placeholder);
          articlesLayout.setVisibility(View.VISIBLE);
          Glide.with(context)
              .setDefaultRequestOptions(requestOptions)
              .load(articlesListChild.get(position).getArticleImage())
              .into(contentIv);
          toolbar.setVisibility(GONE);
          articlesPager.setVisibility(GONE);
          contentIv.setScaleType(ImageView.ScaleType.FIT_XY);
            contentHeadTv.setText(articlesListChild.get(position).getArticleHeading().trim());
            contentBodyTv.setText(articlesListChild.get(position).getArticleContent().trim());
            contentSourceTv.setText(articlesListChild.get(position).getArticleSource().trim());
          contentSourceTv.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  Uri uri = Uri.parse(articlesListChild.get(position).getArticleSourceLink());
                  Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                  context.startActivity(intent);
              }
           });
    
           articleShareBtn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  Bitmap screenshotBitmap = takeScreenshot((View) view.getTag());
                  saveAndShareScreenshot(screenshotBitmap);
              }
           });
    
           container.addView(viewLayout, 0);
           return viewLayout;
    
       }
    
       private Bitmap takeScreenshot(View root) {
           root.setDrawingCacheEnabled(true);
           Bitmap screenshotBitmap = root.getDrawingCache();
           return screenshotBitmap;
       }
    
       private void saveAndShareScreenshot(Bitmap screenshotBitmap) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            // Save Screenshot
            File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/MyApp Screenshots");
            myDir.mkdir();
            String fname = "Image-" + 1 + ".jpg";
            File file = new File(myDir, fname);
            if (file.exists()) {
                file.delete();
            }
            try {
                file.createNewFile();
                FileOutputStream out = new FileOutputStream(file);
                screenshotBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            MediaScannerConnection.scanFile(context, new String[]{file.toString()}, new String[]{file.getName()}, null);
            // Share Screenshot
            file.setReadable(true, false);
            final Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri photoURI = FileProvider.getUriForFile(context, "com.xyz.abcapp.provider", file);
            String shareBody = "Share"
            intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Read this article");
            intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
            intent.putExtra(Intent.EXTRA_STREAM, photoURI);
            intent.setType("image/*");
            context.startActivity(Intent.createChooser(intent,"Share Using"));
        } else {
            Toast.makeText(context, "Permissions not granted", Toast.LENGTH_SHORT).show();
        }
    }