如何从ViewPager当前查看图像?

时间:2017-07-02 06:58:10

标签: java android image picasso

我浏览了SO上的多个主题,问题与我的相似,但无法找到解决方案。我有一个有ViewPager的活动。它使用Picasso在ImageView中加载图像。它工作正常并成功加载图像,我可以刷过它们。但问题是我想保存当前的观看图像或可绘制的。我可以编写保存代码,但为此,我首先必须得到我无法做到的可绘制。

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

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

我尝试过使用它:

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

这也是:

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

我也尝试过 getTag setTag ,但我每次都会得到NullPointerException,尽管我将标签正确设置为 position

1 个答案:

答案 0 :(得分:0)

老实说,你的方法很奇怪。 ViewPager一次至少创建两个页面(因此您可以在上一页和下一页之间平滑滚动),因此您不会以这种方式获得当前活动页面。

所以,方便的方法是:

将此添加到适配器类的顶部

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

将其添加到instantiateItem

的底部

views.put(position, imageView)

将其添加到destroyItem

的底部

views.remove(position, imageView)

通过

获得你的绘画

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