简体   繁体   English

如何从ViewPager获取当前正在查看的图像?

[英]How To Get Currently Viewing Image From ViewPager?

I have browsed multiple threads on SO with issues similar to mine but couldn't find a resolution. 我浏览了关于SO的多个线程,发现了与我类似的问题,但是找不到解决方案。 I have an activity which has a ViewPager. 我有一个具有ViewPager的活动。 It loads an image in ImageView using Picasso. 它使用毕加索将图像加载到ImageView中。 It's working fine and successfully loads the images and I can swipe through them. 它工作正常,可以成功加载图像,我可以在其中滑动。 But the issue is I want to save the current viewing image or drawable. 但是问题是我想保存当前的查看图像或可绘制图像。 I can code for saving but for that, I first have to get drawable which I can't seem to do. 我可以编写代码进行保存,但为此,我首先必须获得可绘制的对象,而这似乎是我无法做到的。

XML: XML:

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_pager"
    android:background="@color/black"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

SwipeActivity.java SwipeActivity.java

public class SwipeActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private ImageView imageView;


    public void save(){
        int currentItem =viewPager.getCurrentItem();
        Drawable drawable = (Drawable) imageView.getDrawable().getCurrent();
        ImageView am = (ImageView)imageView.getTag(currentItem);
        Log.e("Jatt", "save: "+currentItem );
        //Lots of Confustion here. Don't look at this function
        //I have messed it up. But will correct once I get the way
        Bitmap bm = ((BitmapDrawable)am.getDrawable()).getBitmap();
        //Bitmap bm =((BitmapDrawable) drawable).getBitmap();
        storeImage(bm);
    }

    private  File getOutputMediaFile(){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Android/data/");

        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
        File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
        return mediaFile;
    }
    private void storeImage(Bitmap image) {
        String TAG="Jatt";
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            Log.d(TAG,
                    "Error creating media file, check storage permissions: ");// e.getMessage());
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.saveimage, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            save();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_swipe);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(" ");
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        ImagePagerAdapter adapter = new ImagePagerAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(getIntent().getIntExtra("pos",0));
    }

    class ImagePagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Photos.sendToList.length;
        }

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Context context = SwipeActivity.this;
            imageView = new ImageView(context);
            int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
            imageView.setPadding(padding, padding, padding, padding);
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            //imageView.setImageResource(Photos.sendToList[position]);
            Picasso.with(context).load(Photos.sendToList[position]).into(imageView);
            ((ViewPager) container).addView(imageView, 0);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((ImageView) object);
        }
    }
}

I have tried using this: 我试过使用此:

imageView.getDrawable(); //Return a fixed image no matter which image is 
                         // being currently viewed

and this too: 这也是:

imageView.getDrawable().getCurrent(); //Doesn't return currently viewing img

I have also tried getTag and setTag kind of way but I get NullPointerException everytime although I set the tag correctly to position 我也尝试过getTagsetTag的方式,但是每次我都会得到NullPointerException,尽管我将标记正确设置为position

your approach is quite strange to be honest. 老实说,你的方法很奇怪。 ViewPager creates two pages at minimum at once (so you can scroll smoothly between previous and next page), thus you won't get currently active page this way. ViewPager一次最多创建两个页面(因此您可以在上一页和下一页之间平滑滚动),因此您不会以这种方式获得当前活动的页面。

so, easy approach for you will be: 因此,简单的方法是:

adding this to your top of your adapter class 将其添加到适配器类的顶部

HashMap<Integer, ImageView> views = new HashMap();

adding this to the bottom of instantiateItem 将此添加到instantiateItem的底部

views.put(position, imageView)

adding this to the bottom of destroyItem 将此添加到destroyItem的底部

views.remove(position, imageView)

and getting your drawable by doing 并通过做得到您的绘画

ImagePagerAdapter adapter = ((ImagePagerAdapter) viewPager.getAdapter()); Drawable target = ((ImageView) adapter.views.get(viewPager.getCurrentItem())).getDrawable();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM