메뉴 건너뛰기

조회 수 666 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

1. /res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher" />

</android.support.constraint.ConstraintLayout>

▼ 갤러리에서 가져온 사진을 표현하기 위해 ImageView 위젯 하나를 배치하였습니다. 해당 예제에서는 화면에 배치되어 있는 ImageView를 클릭하였을 때 Gallery Activity릃 실행한 뒤 사진을 선택하고 예제 앱 액티비티로 돌아왔을 때 ImageView에 해당 사진을 표현하도록 하겠습니다. 


2. MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE = 0;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.image);

        imageView.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, REQUEST_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if(requestCode == REQUEST_CODE)
        {
            if(resultCode == RESULT_OK)
            {
                try{
                    InputStream in = getContentResolver().openInputStream(data.getData());

                    Bitmap img = BitmapFactory.decodeStream(in);
                    in.close();

                    imageView.setImageBitmap(img);
                }catch(Exception e)
                {

                }
            }
            else if(resultCode == RESULT_CANCELED)
            {
                Toast.makeText(this, "사진 선택 취소", Toast.LENGTH_LONG).show();
            }
        }
    }
}

▼ onCreate() 함수에서는 imageView가 클릭되었을 때 동작 처리를 위한 Click Listener를 생성한 뒤 setOnClickListener() 함수를 통해 생성된 리스너를 등록합니다. onClick() 함수에서는 Intent 객체를 생성하고 갤러리 액티비티 실행하기 위한 정보를 Setting합니다. 갤러리 액티비티로부터 가져온 결과 데이터를 처리하기 위해  StartActivityForResult() 함수를 통해 액티비티를 실행해줍니다. 

 

▼ 갤러리 액티비티로부터 결과 데이터를 처리하기 위해서는 onActivityResult() 함수를 오버라이딩합니다. 해당 함수의 인자는 3개입니다. 첫 번째 인자 RequestCode는 StartActivityForResult() 함수의 두 번째 인자로 넘겨줬던 값과 동일한 값이 넘어옵니다. 두 번째 인자는 resultCode로 사진을 정상적으로 선택하였다면 RESULT_OK 값이 넘어오며 뒤로가기 버튼으로 작업을 취소한 경우 RESULT_CANCELED 값이 넘어옵니다. 해당 코드값을 확인하여 액티비티에서 적절한 처리를 해주면됩니다. 마지막 세 번째 인자로 갤러리 액티비티로부터 넘어온 결과 데이터가 담겨있는 Intent 객체입니다.

 

List of Articles
번호 제목 날짜 조회 수
157 안드로이드 - 색상 리소스 (Color Resource) 추가 </color> file 2021.03.31 551
156 안드로이드 - 뷰페이저(ViewPager) 구현 file 2021.04.02 323
155 안드로이드 - 버튼 이벤트 처리방법 정리 (리스너 구현 및 이벤트 핸들링) file 2021.03.31 343
154 안드로이드 - 문자열 배열 리소스 추가하기 <string-array> file 2021.03.31 811
153 안드로이드 - 문자열 리소스를 활용한 다국어 지원 file 2021.03.31 282
152 안드로이드 - 문자열 리소스(Resource) 추가 및 참조하기 file 2021.03.31 906
151 안드로이드 - 명시적 인텐트(Explicit Intent)와 암시적 인텐트 (Implicit Intent) file 2021.04.01 324
150 안드로이드 - 리스트뷰(ListView) 구현 file 2021.04.01 490
149 안드로이드 - 리사이클러뷰 (RecyclerView) notifyDataSetChanged 실행 시 깜빡 거리는 현상 2021.04.02 746
148 안드로이드 - 리사이클러 뷰(RecyclerView) 구현 file 2021.04.01 388
147 안드로이드 - 리니어 레이아웃 (Linear Layout) file 2021.03.29 319
146 안드로이드 - 랠러티브 레이아웃(Relative Layout) file 2021.03.29 239
145 안드로이드 - 네비게이션 드로어(Navigation Drawer)를 활용하여 슬라이드 메뉴 구현하기 file 2021.04.01 1858
144 안드로이드 - 날짜 및 시간 정보 입력받기 (DatePickerDialog / TimePickerDialog) file 2021.04.01 1762
» 안드로이드 - 갤러리에서 이미지 가져오기 2021.04.02 666
142 안드로이드 - Text 입력 이벤트 처리 - TextWatcher file 2021.04.02 557
141 안드로이드 - switch를 사용법 및 구현 file 2021.04.02 1280
140 안드로이드 - SQLiteDatabase 구현하기 file 2021.04.01 243
139 안드로이드 - SnackBar를 사용해 팝업창 띄우기 file 2021.03.31 282
138 안드로이드 - SharedPreferences에 앱 정보 저장하기 file 2021.04.02 395
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved