2014年5月12日 星期一

【Android】Open Gallary By App

startActivity:

   1: Button btn = (Button)rootView.findViewById(R.id.button1);
   2: btn.setOnClickListener(new OnClickListener(){
   3:  
   4:     @Override
   5:     public void onClick(View v) {
   6:         Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
   7:         final int ACTIVITY_SELECT_IMAGE = 1234;
   8:         startActivityForResult(i, ACTIVITY_SELECT_IMAGE); 
   9:     }
  10: });
  11:  
  12: Button btn2 = (Button)rootView.findViewById(R.id.button2);
  13: btn2.setOnClickListener(new OnClickListener(){
  14:  
  15:     @Override
  16:     public void onClick(View v) {
  17:         Intent intent = new Intent();
  18:         intent.setType("image/*");
  19:         intent.setAction(Intent.ACTION_GET_CONTENT);//
  20:         startActivityForResult(Intent.createChooser(intent, "Select Picture"),10);
  21:         
  22:     }
  23:     
  24: });

onActivityResult:


   1: @Override
   2: public void onActivityResult(int requestCode, int resultCode,
   3:         Intent data) {
   4:     Log.i(TAG, "request code:"+resultCode);
   5:     super.onActivityResult(requestCode, resultCode, data);
   6:      Uri selectedImage = null;
   7:     switch(requestCode) { 
   8:     case 1234:
   9:         if(resultCode == RESULT_OK){  
  10:             selectedImage = data.getData();
  11:             Log.i(TAG, "Uri:"+selectedImage);
  12:             
  13:             /* Now you have choosen image in Bitmap format in object "yourSelectedImage". You can use it in way you want! */
  14:         }
  15:     case 10:
  16:          if(resultCode == RESULT_OK){  
  17:                 selectedImage = data.getData();
  18:                 Log.i(TAG, "Uri:"+selectedImage);
  19:          }
  20:         break;
  21:     }
  22:     
  23:     String[] filePathColumn = {MediaStore.Images.Media.DATA};
  24:  
  25:     Cursor cursor = this.getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
  26:     cursor.moveToFirst();
  27:  
  28:     int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
  29:     String filePath = cursor.getString(columnIndex);
  30:     cursor.close();
  31:  
  32:  
  33:     Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
  34:     
  35:     this.imageView.setImageBitmap(yourSelectedImage);
  36: }

沒有留言:

張貼留言