본문 바로가기
안드로이드 자바

[안드로이드 자바] Matisse 라이브러리 사용하기

by teamnova 2023. 1. 24.
728x90

안녕하세요

오늘은 Matisse 라이브러리를 사용해서 이미지 갤러리를 만들어보도록 하겠습니다.

 

1. 라이브러리 등록

repositories {
    jcenter()
}

dependencies {
    implementation 'com.zhihu.android:matisse:$latest_version'
}

2. 권한 설정

android.permission.READ_EXTERNAL_STORAGE
android.permission.WRITE_EXTERNAL_STORAGE

3. 엑티비티 와 레이아웃 세팅

MainActivity

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bind = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(bind.getRoot());

        requestPermission();

        adapter = new Img_adapter(MainActivity.this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
        bind.rv.setLayoutManager(linearLayoutManager);
        bind.rv.setAdapter(adapter);

        bind.btn.setOnClickListener(view -> {
            // 내 커스텀
            Matisse.from(MainActivity.this) # 권한 설정
                    .choose(MimeType.ofAll()) # 이미지 가져오는 종류 설정
                    .countable(true) # 숫자 카운트 설정
                    .maxSelectable(3) # 최대 선택 수 제한
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_USER) # 갤러리 방향제한
                    .thumbnailScale(0.85f) # 미리보기시 썸네일 크기
                    .imageEngine(new GlideEngine()) # 글라이드 호환 설정
                    .showPreview(true) # 미리보기 설정
                    .forResult(1111); # requestcode
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1111 && resultCode == RESULT_OK) {
            List<Uri> image_uri = new ArrayList<>();
            image_uri = Matisse.obtainResult(data);
            for (Uri image : image_uri) {
                adapter.addImage(image);
            }
        }
    }
	
    # Permission 권한 요청
    private void requestPermission(){
        // 마시멜로우 버전 이후라면 권한을 요청해라
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED ) {
            } else {
                String[] permission = {Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE  };
                ActivityCompat.requestPermissions(this, permission, 1);
            }
        }
    }

Img_adapter


public class Img_adapter extends RecyclerView.Adapter<Img_adapter.viewHolder> {
    private ArrayList<Uri> items = new ArrayList<>();
    private Context context;


    public Img_adapter(Context context) {
        this.context = context;
    }

    public void addImage(Uri string) {
        items.add(string);
        notifyItemInserted(items.size());
    }

    @NonNull
    @Override
    public Img_adapter.viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_img, parent, false);
        return new viewHolder(view, this);
    }

    @Override
    public void onBindViewHolder(@NonNull Img_adapter.viewHolder holder, int position) {
        Uri str = items.get(position);
        Glide.with(context).load(str).into(holder.img);
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public class viewHolder extends RecyclerView.ViewHolder {
        private ImageView img;
        public viewHolder(@NonNull View itemView, Img_adapter img_adapter) {
            super(itemView);
            img = itemView.findViewById(R.id.item_img);
        }
    }
}

activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="140dp"
        android:text="이미지 가지러가기"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginBottom="184dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

item_img.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/item_img"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>