错误的引用触发了Viewpager上的OnClick侦听器

时间:2019-01-18 06:25:10

标签: android android-viewpager

我在MainActivity中有一个ViewPager,并且正在向其中加载内容,这工作正常,但是当我在按钮上设置onClickListener来获取该特定页面的屏幕截图时,该屏幕截图已被捕获,但是在下一页中,我已经调试了代码,但是找不到确切的原因。在这里,我附上代码以供参考。有人可以检查我在哪里做错了吗?

我尝试在此平台上搜索问题,但是似乎没有一个解决我的问题的方法。

适配器代码

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>

我无法获取当前viewpager项目的屏幕截图。

2 个答案:

答案 0 :(得分:0)

layout.setDrawingCacheEnabled(true);
    layout.setDrawingCacheQuality(LinearLayout.DRAWING_CACHE_QUALITY_HIGH);

在完全绘制其布局后,使用ViewTreeObserver进行回叫。

    ViewTreeObserver vto = layout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            getDrawingBitmap();
        }
    });

    public void getDrawingBitmap () {
        LinearLayout mainLayout = (LinearLayout)
                findViewById(R.id.app_parent_layout);
        Bitmap b = mainLayout.getDrawingCache();

        File file = saveBitmapAsFile(b);

        Intent resultIntent = new Intent();
        resultIntent.putExtra("FullFileName", file.getAbsolutePath());
        setResult(Activity.RESULT_OK, resultIntent);
        finish();
    }

答案 1 :(得分:0)

作为@MikeM。在评论中建议

嗯,有几种不同的方法可以做到这一点。假设articleShareBtn在每个单独的页面中,可能最简单的方法是在rootView = ...行之后的articleShareBtn.setTag(rootView),然后将您的方法更改为私有Bitmap takeScreenshot(View root){root.setDrawingCacheEnabled(true); ...},然后在onClick()中,将其命名为Bitmap screenshotBitmap = takeScreenshot((View)view.getTag());。跟着我?否则,您可以保留一个Map所有页面的Views,并使用当前索引来获取正确的索引。如有必要,还有其他几种方法。

我知道了。 我更新的适配器代码是

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();
    }
}