从galleryView中选择imageview

时间:2013-07-15 12:20:20

标签: android imageview galleryview

我想知道如何获得图库视图中显示的图像的参考?例如,我希望添加一个按钮来旋转图像,但我不明白如何选择它。我认为getItemViewType是可能的,但我不明白它会返回什么。

活动

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.image_show);
    app = this;
    final Gallery gallery = (Gallery) findViewById(R.id.gallery);

    // EDGES ARE INVISIBLE

    gallery.setHorizontalFadingEdgeEnabled(false);

    ia = new ImageAdapterr(this);
    gallery.setAdapter(ia);
    // ia.getView(position, convertView, parent);
    final int length = UILApplication.photo_buffer_big.size();
    Button back_btn = (Button) findViewById(R.id.analitics_back_btn);
    back_btn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
    final TextView img_counter_tv = (TextView) findViewById(R.id.img_counter);
    img_counter_tv.setText(p + 1 + "/" + length);
    Button nextButton = (Button) findViewById(R.id.next_btn);
    nextButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (p < length - 1) {
                p++;
            } else {
                p = 0;
            }
            gallery.setSelection(p, true);
            img_counter_tv.setText(p + 1 + "/" + length);
        }
    });

    Button backButton = (Button) findViewById(R.id.back_btn);
    backButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (p == 0) {
                p = length - 1;
            } else {
                p--;
            }
            gallery.setSelection(p, true);
            img_counter_tv.setText(p + 1 + "/" + length);

        }
    });
}

public void rotateS(View v) {
    // int q = (ia.getItemViewType(p));

    // Bitmap b = ((BitmapDrawable) imView.getDrawable()).getBitmap();
    Bitmap b = ((BitmapDrawable) images.get(p).getDrawable()).getBitmap();
    Matrix matrix = new Matrix();
    matrix.postRotate(geg);
    matrix.postScale(0.5f, 0.5f);
    Bitmap bMapRotate = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true);
    imView.setImageBitmap(bMapRotate);
    geg = (geg+90)%360;
}

适配器

class ImageAdapterr extends BaseAdapter {

    /** The parent context */
    private Context myContext;

    /** Simple Constructor saving the 'parent' context. */
    public ImageAdapterr(Context c) {
        this.myContext = c;
    }

    /** Returns the amount of images we have defined. */
    public int getCount() {
        return UILApplication.photo_buffer_big.size();
    }

    /* Use the array-Positions as unique IDs */
    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    /**
     * Returns a new ImageView to be displayed, depending on the position
     * passed.
     */
    // public ImageView getImage(int position, View convertView, ViewGroup parent) {
    //          
    // }
    public View getView(int position, View convertView, ViewGroup parent) {

        ImageView imView = new ImageView(this.myContext);

        imgPos = position;
        AsyncLoad imLoad = new AsyncLoad();
        imLoad.execute();
        try {
            bm = imLoad.get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (bm != null) {
            imView.setImageBitmap(bm);
        } else if (bm == null) {
            imView.setImageResource(R.drawable.logo);
        }
        /* Image should be scaled as width/height are set. */
        // imView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        /* Set the Width/Height of the ImageView. */
        imView.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.MATCH_PARENT));
        imView.setOnTouchListener(new OnTouchListener() {
            private static final String TAG = "Touch";
            // These matrices will be used to move and zoom image
            Matrix matrix = new Matrix();
            Matrix savedMatrix = new Matrix();
            PointF start = new PointF();
            public PointF mid = new PointF();

            // We can be in one of these 3 states
            public static final int NONE = 0;
            public static final int DRAG = 1;
            public static final int ZOOM = 2;
            public int mode = NONE;

            float oldDist;

            public boolean onTouch(View v, MotionEvent event) {

                ImageView view = (ImageView) v;
                view.setScaleType(ImageView.ScaleType.MATRIX);
                switch (event.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_DOWN:

                        savedMatrix.set(matrix);
                        start.set(event.getX(), event.getY());
                        Log.d(TAG, "mode=DRAG");
                        mode = DRAG;
                        break;

                    case MotionEvent.ACTION_POINTER_DOWN:

                        oldDist = spacing(event);
                        Log.d(TAG, "oldDist=" + oldDist);
                        if (oldDist > 10f) {

                            savedMatrix.set(matrix);
                            midPoint(mid, event);
                            mode = ZOOM;
                            Log.d(TAG, "mode=ZOOM");
                        }
                        break;

                    case MotionEvent.ACTION_MOVE:

                        if (mode == DRAG) {

                            matrix.set(savedMatrix);
                            matrix.postTranslate(event.getX() - start.x,
                                    event.getY() - start.y);
                        } else if (mode == ZOOM) {

                            float newDist = spacing(event);
                            Log.d(TAG, "newDist=" + newDist);
                            if (newDist > 10f) {

                                matrix.set(savedMatrix);
                                float scale = newDist / oldDist;
                                matrix.postScale(scale, scale, mid.x, mid.y);
                            }
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_POINTER_UP:

                        mode = NONE;
                        Log.d(TAG, "mode=NONE");
                        break;
                }

                // Perform the transformation
                view.setImageMatrix(matrix);

                return true; // indicate event was handled
            }

            private float spacing(MotionEvent event) {
                float x = event.getX(0) - event.getX(1);
                float y = event.getY(0) - event.getY(1);
                return FloatMath.sqrt(x * x + y * y);
            }

            private void midPoint(PointF point, MotionEvent event) {

                float x = event.getX(0) + event.getX(1);
                float y = event.getY(0) + event.getY(1);
                point.set(x / 2, y / 2);
            }

        });

        images.add(imView);
        Log.d("images","id "+ imView.getId());
        Log.d("images","size "+ images.size());
        return imView;
    }

    /**
     * Returns the size (0.0f to 1.0f) of the views depending on the
     * 'offset' to the center.
     */
    public float getScale(boolean focused, int offset) {
        /* Formula: 1 / (2 ^ offset) */
        return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
    }

    class AsyncLoad extends AsyncTask<Void, Void, Bitmap> {
        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(app);
            pd.setOwnerActivity(app);
            pd.setTitle("Идет загрузка...");
            pd.setCancelable(true);
            pd.show();
        }

        @Override
        protected Bitmap doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            try {
                /*
                 * Open a new URL and get the InputStream to load data from it.
                 */
                URL aURL = new URL(UILApplication.photo_buffer_big.get(imgPos));
                URLConnection conn = aURL.openConnection();
                conn.connect();
                InputStream is = conn.getInputStream();
                /* Buffered is always good for a performance plus. */
                BufferedInputStream bis = new BufferedInputStream(is);
                /* Decode url-data to a bitmap. */
                bm = BitmapFactory.decodeStream(bis);
                bis.close();
                is.close();
                /* Apply the Bitmap to the ImageView that will be returned. */
                // imView.setImageBitmap(bm);
            } catch (IOException e) {
                // imView.setImageResource(R.drawable.logo);
                bm = null;
                Log.e("DEBUGTAG", "Remote Image Exception", e);
            }
            return bm;
        }

        @Override
        protected void onPostExecute(Bitmap arg0) {
            pd.dismiss();
        }

    }
}

4 个答案:

答案 0 :(得分:0)

This code will be use for that ...try it ....

On Button click
-------------------------------------------------------------------------------  
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(i, RESULT_LOAD_IMAGE);

-----------------------------------------------------------------------------          
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);

 if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
     Uri selectedImage = data.getData();
     String[] filePathColumn = { MediaStore.Images.Media.DATA };

     Cursor cursor = getContentResolver().query(selectedImage,
             filePathColumn, null, null, null);
     cursor.moveToFirst();

     int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
     String picturePath = cursor.getString(columnIndex);
     cursor.close();

     // String picturePath contains the path of selected Image
 }

答案 1 :(得分:0)

This code will work for that.. using This click listener you can do that.

gridview.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

imageView.setImageResource(pics[arg2]);

}    });

答案 2 :(得分:0)

You Can store your all image like this...and u can get ur position and you can set your   image in next activity or anythin else..Try it it will work..i did implement it..
int[] arrImage = { R.drawable.btn_eight_c, R.drawable.btn_seven_c,
        R.drawable.btn_six_c, R.drawable.btn_five_c, R.drawable.btn_four_c,
        R.drawable.btn_three_c, R.drawable.btn_two_c, R.drawable.btn_one_c, };

答案 3 :(得分:0)

好的,答案非常简单

克里特岛类字段:

private ImageView currrent;

为图库添加onItemSelectedListener

gallery.setOnItemSelectedListener(new OnItemSelectedListener() { 

      public void  onItemSelected  (AdapterView<?>  parent, View  v, int position, long id) {
          geg = 90;
          current = (ImageView) v;
        }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    }
    });

现在,current将始终引用galleryview显示的图像,您可以随意执行任何操作。