2014-04-17 2 views
1

Я хочу сохранить LinearLayout, содержащий два ImageView, и в этом ImageViews есть два разных изображения. Я хочу сохранить этот макет в gallery.Can никому, пожалуйста, как может я сделать этоКак сохранить макет в качестве изображения в галерее?

Код, который я использовал:

в XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" 
    > 

    <LinearLayout android:id="@+id/linear2" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_weight="1" 
    > 

    <ImageView 
     android:id="@+id/imageView21" 
     android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
     android:layout_weight="1" 
     android:src="@drawable/ic_launcher" /> 

    <ImageView 
     android:id="@+id/imageView22" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_weight="1" 
     android:src="@drawable/ic_launcher" /> 

    </LinearLayout> 

    <RelativeLayout android:id="@+id/linear2" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_weight="5" 
    > 

    <Button 
     android:id="@+id/savelayout2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:text="Save" /> 

    </RelativeLayout> 

</LinearLayout> 

в классе деятельности .. .

public class LayoutDisplay2 extends Activity { 

    Button save; 
    LinearLayout ll; 
    ImageView iv1, iv2; 
    private static int RESULT_LOAD_IMAGE1 = 1; 
    private static int RESULT_LOAD_IMAGE2 = 2; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.layout2); 
     ll = (LinearLayout) findViewById(R.id.linear2); 
     save = (Button) findViewById(R.id.savelayout2); 
     save.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       ll.setDrawingCacheEnabled(true); 
       Bitmap bitmap = ll.getDrawingCache(); 

       String root = Environment.getExternalStorageDirectory() 
         .toString(); 
       File newDir = new File(root + "/saved_picture"); 
       newDir.mkdirs(); 
       Random gen = new Random(); 
       int n = 10000; 
       n = gen.nextInt(n); 
       String fotoname = n + ".jpg"; 
       File file = new File(newDir, fotoname); 
       String s = file.getAbsolutePath(); 
       Log.i("Path of saved image.", s); 
       System.err.print("Path of saved image." + s); 

       try { 
        FileOutputStream out = new FileOutputStream(file); 
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); 
        out.flush(); 
        Toast.makeText(getApplicationContext(), "Photo Saved", 
          Toast.LENGTH_SHORT).show(); 
        out.close(); 
       } catch (Exception e) { 
        Toast.makeText(getApplicationContext(), "Photo Saved", 
          Toast.LENGTH_SHORT).show(); 
        Log.e("Exception", e.toString()); 
       } 
      } 

     }); 
     iv1 = (ImageView) findViewById(R.id.imageView21); 
     iv1.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       Intent i = new Intent(
         Intent.ACTION_PICK, 
         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

       startActivityForResult(i, RESULT_LOAD_IMAGE1); 
      } 
     }); 
     iv2 = (ImageView) findViewById(R.id.imageView22); 
     iv2.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 

       Intent in = new Intent(
         Intent.ACTION_PICK, 
         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 

       startActivityForResult(in, RESULT_LOAD_IMAGE2); 
      } 
     }); 

    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     // TODO Auto-generated method stub 
     super.onActivityResult(requestCode, resultCode, data); 

     if (requestCode == RESULT_LOAD_IMAGE1 && 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(); 

      try { 

       iv1.setImageBitmap(BitmapFactory.decodeFile(picturePath)); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     } 
     if (requestCode == RESULT_LOAD_IMAGE2 && resultCode == RESULT_OK 
       && null != data) { 
      Uri selectedImage = data.getData(); 
      String[] filePathColumn = { MediaStore.Images.Media.DATA }; 
      Toast.makeText(getApplicationContext(), "in second", 
        Toast.LENGTH_SHORT).show(); 
      Log.i("Second", "in second"); 
      Cursor cursor = getContentResolver().query(selectedImage, 
        filePathColumn, null, null, null); 
      cursor.moveToFirst(); 

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      String picturePath = cursor.getString(columnIndex); 
      cursor.close(); 
      try { 
       iv2.setImageBitmap(BitmapFactory.decodeFile(picturePath)); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 

    } 

} 

исключение я получаю:

04-17 13:19:33.908: I/Path of saved image.(30459): /mnt/sdcard/saved_picture/3400.jpg 
04-17 13:19:33.918: E/Exception(30459): java.io.FileNotFoundException: /mnt/sdcard/saved_picture/3400.jpg (No such file or directory) 
+1

означает, что вы хотите взять скриншот и сохранить в галерее? – Riser

+0

любезно проверьте весь мой код, и если вы не возражаете выполнить его один раз. Я хочу сохранить LinearLayout android: id = "@ + id/linear2" в галерее. Этот макет содержит два изображения –

+0

, которые я пробовал, и он работает. Вы упомянули разрешение на запись в файл манифеста? – Riser

ответ

0

просто добавьте ниже разрешения в вашем файле манифеста:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 

EDIT:

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 

if(isSDPresent) 
{ 
    // yes 
} 
else 
{ 
// No 
} 
+0

в любом случае, какой путь я дам –

+0

, следуйте этому http://stackoverflow.com/questions/13161470/saving-file-in-internal-storage-android – Riser

+0

Спасибо за вашу помощь. У меня есть еще один запрос, который показывает изображение в очень небольшом размере в галерее, почему вы так можете рассказать об этом и как я могу показать изображение, сохраненное в галерее на полноэкранном режиме, и сделать так много времени в галерее? –

Смежные вопросы