안드로이드 자바
[JAVA][Android]ActivityResultLauncher 앨범 에서 사진 선택 후 이미지뷰에 이미지 넣기
teamnova
2024. 7. 30. 12:00
728x90
인텐트로 안드로이드 사진앨범을 실행해서 하는 것이 아닌 ActivityResultLauncher 으로 해보겠습니다.
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class test extends AppCompatActivity {
ImageView selectedImageView;
ActivityResultLauncher<PickVisualMediaRequest> pickMultipleMedia;
Button selectPhotosButton;
String TAG = "test";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
selectedImageView = findViewById(R.id.selectedImageView);
selectPhotosButton = findViewById(R.id.selectPhotosButton);
// 다중 선택 모드로 사진 선택기 활동 등록
selectPhotosButton.setOnClickListener(v -> {
// 사진 선택기를 실행하고 사용자가 이미지와 비디오를 선택하도록 합니다.
pickMultipleMedia.launch(new PickVisualMediaRequest.Builder()
.setMediaType(ActivityResultContracts.PickVisualMedia.ImageAndVideo.INSTANCE)
.build());
});
select_img(1);
}
void select_img(int num) {
if (num == 1) {
num = 2;
}
pickMultipleMedia = registerForActivityResult(new ActivityResultContracts.PickMultipleVisualMedia(num), uris -> {
// 사용자가 미디어 항목을 선택하거나 사진 선택기를 닫으면 콜백이 호출됩니다.
if (!uris.isEmpty()) {
Log.d(TAG, "Number of items selected: " + uris.size());
Log.d(TAG, "items selected Uris : " + uris.toString());
// 첫 번째 선택된 이미지를 ImageView에 표시합니다.
selectedImageView.setImageURI(uris.get(0));
} else {
Log.d(TAG, "No media selected");
}
});
}
}
<!-- res/layout/activity_main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/selectPhotosButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Photos" />
<ImageView
android:id="@+id/selectedImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:scaleType="centerCrop" />
</LinearLayout>
시연영상