使用 Glide 从 Uri 设置背景布局

Set background layout from Uri with Glide

我正在尝试使用选取的图库图像更改背景布局。到目前为止,我正在从图库中挑选图像,并且正在使用意图将字符串发送到 MainActivity。但是在 Activity 中,Glide 根本不工作。在调试模式下,我没有任何异常。

第一个Activity

private void openGallery() {
    Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(gallery, PICK_IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
        Uri imageUri = data.getData();

        SharedPreferences sharedPreferences = getSharedPreferences("PREFS_BACK_DISK", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("backgroundFromDisk", String.valueOf(imageUri));
        editor.apply();
        Intent intent = new Intent(Main.this, SettingsActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        Toast.makeText(Main.this, "Theme changed", Toast.LENGTH_LONG).show();
    }
}

第二个Activity(onCreate()方法)

SharedPreferences prefs3 = getSharedPreferences("PREFS_BACK_DISK", MODE_PRIVATE);
String stringBackgroundFromDisk = prefs3.getString("backgroundFromDisk", "");
if (stringBackgroundFromDisk.isEmpty() || (stringBackgroundFromDisk == null)) {
    
} else {
    Glide.with(this)
            .load((stringBackgroundFromDisk))
            .into(new CustomTarget<Drawable>() {
                @Override
                public void onResourceReady(@NonNull Drawable resource,
                                            @Nullable Transition<? super Drawable> transition) {

                    ConstraintLayout constraintLayout = findViewById(R.id.contraint_layout);
                    constraintLayout.setBackground(resource);
                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {

                }
            });
}

似乎在选取图像时,getData() 并未 return 实际文件位置。参考:Get filepath and filename of selected gallery image in Android