【问题标题】:Pass gallery image data from Activity to DialogPreferences将画廊图像数据从 Activity 传递到 Dialog Preferences
【发布时间】:2016-05-20 04:34:52
【问题描述】:

我创建了一个设置活动。我在其中有很多片段。 其中之一具有徽标设置(DialogPreferences),我需要在其中从图库中选择图像,并且需要将该图像显示到 DialogPreferences 的 ImageView 中。

现在,我在设置活动的 onActivityResult 中获取图库图片。但是,我需要将图像数据放入 Configuration(Fragment)-> LogoPreferences (DialogPreferences)。

所以,我的问题是,如何将图像数据从 onActivityResult(Activity)获取到 LogoPreferences(即 DialogPreference,它位于 Configuration 片段内)。

提前致谢。

【问题讨论】:

    标签: android image android-fragments


    【解决方案1】:

    您可以将从onActivityResult() 获得的Bitmap 图像转换为ByteArray,然后将该数组转换回您的LogoPreferences 活动(或您想要数据到的任何活动)去)。您可以这样做:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // Check to see the result is from the activity you are targeting
        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            try {
                Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
                Log.i("Image Path", selectedImage.getPath());
    
                // Convert bitmap to byte array
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 0 /*ignored if PNG*/, bos);
                byte[] bitmapdata = bos.toByteArray();
    
                Bundle b = new Bundle();
                b.putByteArray("byteArray", bitmapdata);
                Intent intent = new Intent(this, LogoPreferences.class);
                intent.putExtras(b);
                startActivity(intent);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    然后要在LogoPreferences 活动中解码该字节数组,您可以这样做:

    if(getIntent().hasExtra("byteArray")) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(
                    getIntent().getByteArrayExtra("byteArray"), 0, getIntent().getByteArrayExtra("byteArray").length);
            // Optionally set the Bitmap to an ImageView
            ImageView imv = new ImageView(this);
            imv.setImageBitmap(bitmap);
          }
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多