簡體   English   中英

如何替換 startActivityForResult 因為它現在已棄用這是我完成項目所需的最后一塊

[英]how to replace the startActivityForResult because its now deprecated this is the last piece i need to finish up my project

如何用 ActivityResultLauncher 替換它。 對不起,我只是編碼和編程的新手。

SelectImageGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent();

            intent.setType("image/*");

            intent.setAction(Intent.ACTION_GET_CONTENT);

            startActivityForResult(Intent.createChooser(intent, "Select Image From Gallery"), 1);

        }
    });

您需要使用以下Kotlin代碼在onCreate之外注冊活動結果

   val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->

                // Callback after selecting image
                // Do whatever you want to do with uri

            }
        }
    }

現在,當您想打開圖庫以選擇圖像時,而不是startActivityForResult(..)調用下面的方法

 getContent.launch("image/*")
SelectImageGallery.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.setType("image/*");

        intent.setAction(Intent.ACTION_GET_CONTENT);

        result.launch(Intent.createChooser(intent, "Select Image From Gallery"));

    }
});

在與偵聽器相同的方法中:

    ActivityResultLauncher<String> result = registerForActivityResult(
        new ActivityResultContracts.GetContent(),
        new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                //DO whatever with received image content scheme Uri
            }
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM