커뮤니티 어플이나 카톡같은 SNS전용 어플등을 보면 프로필사진은 필수다.
오늘은 이 프로필사진을 직접 갤러리에서 가져와 ImageView에 삽입하는 과정을 처음부터 끝까지 설명하도록 한다. 오랫동안 안드로이드에 손을 놓고있다보니 가물가물하다.
사진을 가져오기위해 갤러리 어플로 이동하는 방법은 Intent를 활용해야 한다. Intent는 Component간의 호출이나 정보 교환을 위해 존재한다.
일단 대충 프로젝트 하나 만들어서 테스트를 위한 기반은 만들어놓자.
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.bino.image.MainActivity" android:orientation="vertical"> <ImageView android:id="@+id/main_imgview" android:layout_width="match_parent" android:layout_height="250dp" android:text="Hello World!" android:background="#eee"/> <Button android:id="@+id/main_image_choose" android:layout_width="match_parent" android:layout_height="100dp" android:text="이미지 선택하기" /> </LinearLayout> | cs |
Activity_Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package com.bino.image; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class Activity_Main extends AppCompatActivity { ImageView Main_imgview; Button Main_image_choose; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Main_imgview = (ImageView) findViewById(R.id.main_imgview); Main_image_choose = (Button) findViewById(R.id.main_image_choose); Main_image_choose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); // 사진 선택어플을 고르도록 함. startActivityForResult(Intent.createChooser(intent, "프로필사진 선택"), 1); }}); } } | cs |
간단하게 요점에 대해서만 설명하도록 한다.
intent.setType()에서 setType()함수는 말그대로 intent되는 타입을 정한다.
코드에서는
intent.setType("image/*");
로서 image를 넣었기때문에 갤러리어플을 요구한다.
그외 나머지는 예를 들면
intent.setType("video/*");
intent.setType("application/*");
등이 있다.
intent.setAction(Intent.ACTION_GET_CONTENT);
윗줄에서 setAction()함수는 intent에 대한 작업을 지정한다.
setType에서 설정한 타입을 통해 파일을 가지고오는 역할을 한다.
이제 그 다음줄을 보자. (33행)
startActivityForResult(Intent.createChooser(intent, "프로필사진 선택"), 1);
최종적으로 명령을 실행하는 부분이다.
startActivityForResult() 함수는 다른 액티비티에서 결과를 수신해준다.
그 값은 나중에 onActivityResult()
함수로 콜백하여 받아온다. (다음 예제에서 등장한다.)
URI는 자료의 위치? 루트를 식별하기위함이다.