簡體   English   中英

如何打開手機圖庫單擊回收器視圖項目(在自定義適配器類中)

[英]How to open phone gallery clicking a recycler view item (inside custom adapter class)

我正在開發一個應用程序,它使用回收器視圖來顯示由圖像和文本組成的項目。 用戶可以添加帶有自定義圖像的項目,在正常活動中執行此操作很容易:

Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            launcher.launch(intent);
private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        result -> {
            if (result.getResultCode() == Activity.RESULT_OK
                    && result.getData() != null) {
                Uri photoUri = result.getData().getData();
                image_to_up = photoUri;
                image_uploaded = true;
                element_image_add.setImageURI(photoUri);
            }
        }
);

但是,如果我想讓用戶編輯回收站視圖項目圖像,那么相同的代碼將無法在自定義適配器中運行,我得到:

Cannot resolve method 'registerForActivityResult' in Adapter

那么,我該怎么做呢? 如何讓用戶在自定義適配器 class 中打開圖庫和 select 圖像?

在您的活動 class 中定義它:

private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == Activity.RESULT_OK
                && result.getData() != null) {
            Uri photoUri = result.getData().getData();
            image_to_up = photoUri;
            image_uploaded = true;
            element_image_add.setImageURI(photoUri);
        }
    }

);

然后在調用此啟動器的活動 class 中創建一個 function,然后從適配器 class 調用此 function:

public void launch_func() {
   Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
   launcher.launch(intent);
}

基本上你不能調用適配器內部的方法,所以你從你的活動 class 中調用它,它不是最漂亮的,但它應該可以工作。

您需要一個活動引用才能使用適配器內的 registerForActivityResult 方法。 使用 Adapter 的構造函數傳遞 Activity 變量並像這樣使用它:

ActivityResultLauncher<Intent> launcher = ((YourActivityClass) activity).registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == Activity.RESULT_OK
                && result.getData() != null) {
            //your logic
        }
    });

暫無
暫無

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

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