├── .gitignore ├── .idea ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── gradle.xml ├── jarRepositories.xml ├── misc.xml ├── runConfigurations.xml └── vcs.xml ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── jeongdaeri │ │ └── unsplash_app_tutorial │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── jeongdaeri │ │ │ └── unsplash_app_tutorial │ │ │ ├── App.kt │ │ │ ├── activities │ │ │ ├── MainActivity.kt │ │ │ └── PhotoCollectionActivity.kt │ │ │ ├── model │ │ │ ├── Photo.kt │ │ │ └── SearchData.kt │ │ │ ├── recyclerview │ │ │ ├── ISearchHistoryRecyclerView.kt │ │ │ ├── PhotoGridRecyeclerViewAdapter.kt │ │ │ ├── PhotoItemViewHolder.kt │ │ │ ├── SearchHistoryRecyclerViewAdapter.kt │ │ │ └── SearchItemViewHolder.kt │ │ │ ├── retrofit │ │ │ ├── IRetrofit.kt │ │ │ ├── RetrofitClient.kt │ │ │ └── RetrofitManager.kt │ │ │ └── utils │ │ │ ├── Constants.kt │ │ │ ├── Extensions.kt │ │ │ └── SharedPrefManager.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ ├── ic_baseline_add_24.xml │ │ ├── ic_baseline_cancel_24.xml │ │ ├── ic_baseline_delete_outline_24.xml │ │ ├── ic_baseline_favorite_24.xml │ │ ├── ic_baseline_insert_photo_24.xml │ │ ├── ic_baseline_menu_24.xml │ │ ├── ic_baseline_more_vert_24.xml │ │ ├── ic_baseline_search_24.xml │ │ ├── ic_launcher_background.xml │ │ ├── ic_person_black_24dp.xml │ │ ├── ic_photo_library_black_24dp.xml │ │ ├── ic_unsplash.xml │ │ ├── rounded_bg_gray.xml │ │ └── rounded_bg_pink.xml │ │ ├── layout │ │ ├── activity_main.xml │ │ ├── activity_photo_collection.xml │ │ ├── layout_button_search.xml │ │ ├── layout_photo_item.xml │ │ └── layout_search_item.xml │ │ ├── menu │ │ └── top_app_bar_menu.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── jeongdaeri │ └── unsplash_app_tutorial │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 20 | 22 | 23 | 24 | 26 | 27 | 28 |
29 | 30 | 31 | 32 | xmlns:android 33 | 34 | ^$ 35 | 36 | 37 | 38 |
39 |
40 | 41 | 42 | 43 | xmlns:.* 44 | 45 | ^$ 46 | 47 | 48 | BY_NAME 49 | 50 |
51 |
52 | 53 | 54 | 55 | .*:id 56 | 57 | http://schemas.android.com/apk/res/android 58 | 59 | 60 | 61 |
62 |
63 | 64 | 65 | 66 | .*:name 67 | 68 | http://schemas.android.com/apk/res/android 69 | 70 | 71 | 72 |
73 |
74 | 75 | 76 | 77 | name 78 | 79 | ^$ 80 | 81 | 82 | 83 |
84 |
85 | 86 | 87 | 88 | style 89 | 90 | ^$ 91 | 92 | 93 | 94 |
95 |
96 | 97 | 98 | 99 | .* 100 | 101 | ^$ 102 | 103 | 104 | BY_NAME 105 | 106 |
107 |
108 | 109 | 110 | 111 | .* 112 | 113 | http://schemas.android.com/apk/res/android 114 | 115 | 116 | ANDROID_ATTRIBUTE_ORDER 117 | 118 |
119 |
120 | 121 | 122 | 123 | .* 124 | 125 | .* 126 | 127 | 128 | BY_NAME 129 | 130 |
131 |
132 |
133 |
134 | 135 | 137 |
138 |
-------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | 24 | 25 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | 5 | android { 6 | compileSdkVersion 29 7 | buildToolsVersion "29.0.3" 8 | 9 | defaultConfig { 10 | applicationId "com.jeongdaeri.unsplash_app_tutorial" 11 | minSdkVersion 26 12 | targetSdkVersion 29 13 | versionCode 1 14 | versionName "1.0" 15 | 16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | 26 | compileOptions{ 27 | sourceCompatibility JavaVersion.VERSION_1_8 28 | targetCompatibility JavaVersion.VERSION_1_8 29 | } 30 | 31 | 32 | } 33 | 34 | dependencies { 35 | implementation fileTree(dir: 'libs', include: ['*.jar']) 36 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 37 | implementation 'androidx.appcompat:appcompat:1.1.0' 38 | implementation 'androidx.core:core-ktx:1.3.1' 39 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 40 | testImplementation 'junit:junit:4.12' 41 | androidTestImplementation 'androidx.test.ext:junit:1.1.1' 42 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 43 | 44 | 45 | // 메테리얼 46 | implementation 'com.google.android.material:material:1.1.0' 47 | 48 | // 레트로핏 49 | def retrofit_version = "2.8.1" 50 | implementation "com.squareup.retrofit2:retrofit:$retrofit_version" 51 | // gson 컨버터 52 | implementation "com.squareup.retrofit2:converter-gson:$retrofit_version" 53 | 54 | // 레트로핏 로깅 인터셉터 55 | implementation "com.squareup.okhttp3:logging-interceptor:4.8.1" 56 | 57 | // 글라이드 이미지 라이브러리 58 | implementation 'com.github.bumptech.glide:glide:4.11.0' 59 | annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0' 60 | 61 | // Rx 62 | // rx 자바 - 메인 63 | 64 | implementation "io.reactivex.rxjava3:rxjava:3.0.6" 65 | // rx 코틀린 - 추가 66 | implementation "io.reactivex.rxjava3:rxkotlin:3.0.0" 67 | 68 | // rx 안드로이드 - 스레드 - 스케쥴러 69 | implementation 'io.reactivex.rxjava3:rxandroid:3.0.0' 70 | 71 | // edittext 등의 안드로이드 뷰 컴포넌트들과 연결 72 | // rx 바인딩 73 | implementation 'com.jakewharton.rxbinding4:rxbinding:4.0.0' 74 | 75 | 76 | // 코루틴 77 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9' 78 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.0-M1' 79 | 80 | 81 | } 82 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/jeongdaeri/unsplash_app_tutorial/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.jeongdaeri.unsplash_app_tutorial", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/App.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial 2 | 3 | import android.app.Application 4 | 5 | class App : Application() { 6 | 7 | companion object{ 8 | lateinit var instance: App 9 | private set 10 | } 11 | 12 | override fun onCreate() { 13 | super.onCreate() 14 | instance = this 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/activities/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.activities 2 | 3 | import android.content.Intent 4 | import androidx.appcompat.app.AppCompatActivity 5 | import android.os.Bundle 6 | import android.util.Log 7 | import android.view.View 8 | import android.widget.Toast 9 | import com.jeongdaeri.unsplash_app_tutorial.R 10 | import com.jeongdaeri.unsplash_app_tutorial.retrofit.RetrofitManager 11 | import com.jeongdaeri.unsplash_app_tutorial.utils.Constants.TAG 12 | import com.jeongdaeri.unsplash_app_tutorial.utils.RESPONSE_STATUS 13 | import com.jeongdaeri.unsplash_app_tutorial.utils.SEARCH_TYPE 14 | import com.jeongdaeri.unsplash_app_tutorial.utils.onMyTextChanged 15 | import kotlinx.android.synthetic.main.activity_main.* 16 | import kotlinx.android.synthetic.main.layout_button_search.* 17 | 18 | class MainActivity : AppCompatActivity() { 19 | 20 | 21 | 22 | private var currentSearchType: SEARCH_TYPE = SEARCH_TYPE.PHOTO 23 | 24 | 25 | override fun onCreate(savedInstanceState: Bundle?) { 26 | super.onCreate(savedInstanceState) 27 | setContentView(R.layout.activity_main) 28 | 29 | Log.d(TAG, "MainActivity - onCreate() called") 30 | 31 | // 라디오 그룹 가져오기 32 | search_term_radio_group.setOnCheckedChangeListener { _, checkedId -> 33 | 34 | 35 | // switch 문 36 | when(checkedId) { 37 | R.id.photo_search_radio_btn -> { 38 | Log.d(TAG, "사진검색 버튼 클릭!") 39 | search_term_text_layout.hint = "사진검색" 40 | search_term_text_layout.startIconDrawable = resources.getDrawable( 41 | R.drawable.ic_photo_library_black_24dp, resources.newTheme()) 42 | this.currentSearchType = SEARCH_TYPE.PHOTO 43 | } 44 | 45 | R.id.user_search_radio_btn -> { 46 | Log.d(TAG, "사용자검색 버튼 클릭!") 47 | search_term_text_layout.hint = "사용자검색" 48 | search_term_text_layout.startIconDrawable = resources.getDrawable( 49 | R.drawable.ic_person_black_24dp, resources.newTheme()) 50 | this.currentSearchType = SEARCH_TYPE.USER 51 | } 52 | } 53 | Log.d(TAG, "MainActivity - OnCheckedChanged() called / currentSearchType : $currentSearchType") 54 | } 55 | 56 | 57 | // 텍스트가 변경이 되었을때 58 | search_term_edit_text.onMyTextChanged { 59 | 60 | // 입력된 글자가 하나라도 있다면 61 | if(it.toString().count() > 0){ 62 | // 검색 버튼을 보여준다. 63 | frame_search_btn.visibility = View.VISIBLE 64 | search_term_text_layout.helperText = " " 65 | 66 | 67 | 68 | // 스크롤뷰를 올린다. 69 | main_scrollview.scrollTo(0, 200) 70 | 71 | } else { 72 | frame_search_btn.visibility = View.INVISIBLE 73 | search_term_text_layout.helperText = "검색어를 입력해주세요" 74 | } 75 | 76 | if (it.toString().count() == 12) { 77 | Log.d(TAG, "MainActivity - 에러 띄우기 ") 78 | Toast.makeText(this, "검색어는 12자 까지만 입력 가능합니다.", Toast.LENGTH_SHORT).show() 79 | } 80 | 81 | } 82 | 83 | // 검색 버튼 클릭시 84 | btn_search.setOnClickListener { 85 | Log.d(TAG, "MainActivity - 검색 버튼이 클릭되었다. / currentSearchType : $currentSearchType") 86 | 87 | this.handleSearchButtonUi() 88 | 89 | val userSearchInput = search_term_edit_text.text.toString() 90 | 91 | // 검색 api 호출 92 | RetrofitManager.instance.searchPhotos(searchTerm = search_term_edit_text.text.toString(), completion = { 93 | responseState, responseDataArrayList -> 94 | 95 | when(responseState) { 96 | RESPONSE_STATUS.OKAY -> { 97 | Log.d(TAG, "api 호출 성공 : ${responseDataArrayList?.size}") 98 | 99 | val intent = Intent(this, PhotoCollectionActivity::class.java) 100 | 101 | val bundle = Bundle() 102 | 103 | bundle.putSerializable("photo_array_list", responseDataArrayList) 104 | 105 | intent.putExtra("array_bundle", bundle) 106 | 107 | intent.putExtra("search_term", userSearchInput) 108 | 109 | startActivity(intent) 110 | 111 | } 112 | RESPONSE_STATUS.FAIL -> { 113 | Toast.makeText(this, "api 호출 에러입니다.", Toast.LENGTH_SHORT).show() 114 | Log.d(TAG, "api 호출 실패 : $responseDataArrayList") 115 | } 116 | 117 | RESPONSE_STATUS.NO_CONTENT -> { 118 | Toast.makeText(this, "검색결과가 없습니다." , Toast.LENGTH_SHORT).show() 119 | } 120 | } 121 | 122 | btn_progress.visibility = View.INVISIBLE 123 | btn_search.text = "검색" 124 | search_term_edit_text.setText("") 125 | 126 | }) 127 | 128 | 129 | } 130 | 131 | 132 | 133 | } // onCreate 134 | 135 | 136 | 137 | private fun handleSearchButtonUi(){ 138 | 139 | btn_progress.visibility = View.VISIBLE 140 | 141 | btn_search.text = "" 142 | 143 | // Handler().postDelayed({ 144 | // btn_progress.visibility = View.INVISIBLE 145 | // btn_search.text = "검색" 146 | // }, 1500) 147 | 148 | } 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | } 158 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/activities/PhotoCollectionActivity.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.activities 2 | 3 | import android.app.SearchManager 4 | import android.content.Context 5 | import android.content.Intent 6 | import android.graphics.Color 7 | import android.graphics.Point 8 | import android.os.Bundle 9 | import android.text.InputFilter 10 | import android.util.Log 11 | import android.view.Menu 12 | import android.view.View 13 | import android.widget.CompoundButton 14 | import android.widget.EditText 15 | import android.widget.Toast 16 | import androidx.appcompat.app.AppCompatActivity 17 | import androidx.appcompat.widget.SearchView 18 | import androidx.recyclerview.widget.GridLayoutManager 19 | import androidx.recyclerview.widget.LinearLayoutManager 20 | import com.jakewharton.rxbinding4.widget.textChanges 21 | import com.jeongdaeri.unsplash_app_tutorial.R 22 | import com.jeongdaeri.unsplash_app_tutorial.model.Photo 23 | import com.jeongdaeri.unsplash_app_tutorial.model.SearchData 24 | import com.jeongdaeri.unsplash_app_tutorial.recyclerview.ISearchHistoryRecyclerView 25 | import com.jeongdaeri.unsplash_app_tutorial.recyclerview.PhotoGridRecyeclerViewAdapter 26 | import com.jeongdaeri.unsplash_app_tutorial.recyclerview.SearchHistoryRecyclerViewAdapter 27 | import com.jeongdaeri.unsplash_app_tutorial.retrofit.RetrofitManager 28 | import com.jeongdaeri.unsplash_app_tutorial.utils.Constants.TAG 29 | import com.jeongdaeri.unsplash_app_tutorial.utils.RESPONSE_STATUS 30 | import com.jeongdaeri.unsplash_app_tutorial.utils.SharedPrefManager 31 | import com.jeongdaeri.unsplash_app_tutorial.utils.textChangesToFlow 32 | import com.jeongdaeri.unsplash_app_tutorial.utils.toSimpleString 33 | import io.reactivex.rxjava3.annotations.SchedulerSupport 34 | import io.reactivex.rxjava3.disposables.CompositeDisposable 35 | import io.reactivex.rxjava3.disposables.Disposable 36 | import io.reactivex.rxjava3.kotlin.subscribeBy 37 | import io.reactivex.rxjava3.schedulers.Schedulers 38 | import kotlinx.android.synthetic.main.activity_photo_collection.* 39 | import kotlinx.coroutines.* 40 | import kotlinx.coroutines.flow.debounce 41 | import kotlinx.coroutines.flow.filter 42 | import kotlinx.coroutines.flow.launchIn 43 | import kotlinx.coroutines.flow.onEach 44 | import java.util.* 45 | import java.util.concurrent.TimeUnit 46 | import kotlin.collections.ArrayList 47 | import kotlin.coroutines.CoroutineContext 48 | 49 | class PhotoCollectionActivity: AppCompatActivity(), 50 | SearchView.OnQueryTextListener, 51 | CompoundButton.OnCheckedChangeListener, 52 | View.OnClickListener, 53 | ISearchHistoryRecyclerView 54 | { 55 | 56 | 57 | // 데이터 58 | private var photoList = ArrayList() 59 | 60 | // 검색 기록 배열 61 | private var searchHistoryList = ArrayList() 62 | 63 | // 어답터 64 | // lateinit 을 통해 나중에 메모리에 올라가도 된다. 65 | private lateinit var photoGridRecyeclerViewAdapter: PhotoGridRecyeclerViewAdapter 66 | private lateinit var mySearchHistoryRecyclerViewAdapter: SearchHistoryRecyclerViewAdapter 67 | 68 | 69 | // 서치뷰 70 | private lateinit var mySearchView: SearchView 71 | 72 | // 서치뷰 에딧 텍스트 73 | private lateinit var mySearchViewEditText: EditText 74 | 75 | /* rx 적용부분 76 | // 옵저버블 통합 제거를 위한 CompositeDisposable 77 | private var myCompositeDisposable = CompositeDisposable() 78 | */ 79 | 80 | private var myCoroutineJob : Job = Job() 81 | private val myCoroutineContext: CoroutineContext 82 | get() = Dispatchers.IO + myCoroutineJob 83 | 84 | 85 | override fun onCreate(savedInstanceState: Bundle?) { 86 | super.onCreate(savedInstanceState) 87 | setContentView(R.layout.activity_photo_collection) 88 | 89 | val bundle = intent.getBundleExtra("array_bundle") 90 | 91 | val searchTerm = intent.getStringExtra("search_term") 92 | 93 | Log.d(TAG, "PhotoCollectionActivity - onCreate() called / searchTerm : $searchTerm, photoList.count() : ${photoList.count()}") 94 | 95 | 96 | 97 | 98 | 99 | 100 | search_history_mode_switch.setOnCheckedChangeListener(this) 101 | clear_search_history_buttton.setOnClickListener(this) 102 | 103 | search_history_mode_switch.isChecked = SharedPrefManager.checkSearchHistoryMode() 104 | 105 | top_app_bar.title = searchTerm 106 | 107 | // 액티비티에서 어떤 액션바를 사용할지 설정한다. 108 | setSupportActionBar(top_app_bar) 109 | 110 | photoList = bundle?.getSerializable("photo_array_list") as ArrayList 111 | 112 | 113 | // 사진 리사이클러뷰 세팅 114 | this.photoCollectionRecyclerViewSetting(this.photoList) 115 | 116 | 117 | // 저장된 검색 기록 가져오기 118 | this.searchHistoryList = SharedPrefManager.getSearchHistoryList() as ArrayList 119 | 120 | this.searchHistoryList.forEach { 121 | Log.d(TAG, "저장된 검색 기록 - it.term : ${it.term} , it.timestamp: ${it.timestamp}") 122 | } 123 | 124 | handleSearchViewUi() 125 | 126 | // 검색 기록 리사이클러뷰 준비 127 | this.searchHistoryRecyclerViewSetting(this.searchHistoryList) 128 | 129 | if(searchTerm.isNotEmpty()){ 130 | val term = searchTerm?.let { 131 | it 132 | }?: "" 133 | this.insertSearchTermHistory(term) 134 | } 135 | 136 | 137 | } // onCreate 138 | 139 | override fun onDestroy() { 140 | Log.d(TAG, "PhotoCollectionActivity - onDestroy() called") 141 | /* rx 적용 부분 142 | // 모두 삭제 143 | this.myCompositeDisposable.clear() 144 | */ 145 | myCoroutineContext.cancel() 146 | 147 | super.onDestroy() 148 | } 149 | 150 | 151 | // 검색 기록 리사이클러뷰 준비 152 | private fun searchHistoryRecyclerViewSetting(searchHistoryList: ArrayList){ 153 | Log.d(TAG, "PhotoCollectionActivity - searchHistoryRecyclerViewSetting() called") 154 | 155 | // 156 | this.mySearchHistoryRecyclerViewAdapter = SearchHistoryRecyclerViewAdapter(this) 157 | this.mySearchHistoryRecyclerViewAdapter.submitList(searchHistoryList) 158 | 159 | val myLinearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true) 160 | myLinearLayoutManager.stackFromEnd = true 161 | 162 | search_history_recycler_view.apply { 163 | layoutManager = myLinearLayoutManager 164 | this.scrollToPosition(mySearchHistoryRecyclerViewAdapter.itemCount - 1) 165 | adapter = mySearchHistoryRecyclerViewAdapter 166 | } 167 | 168 | } 169 | 170 | 171 | // 그리드 사진 리사이클러뷰 세팅 172 | private fun photoCollectionRecyclerViewSetting(photoList: ArrayList){ 173 | Log.d(TAG, "PhotoCollectionActivity - photoCollecitonRecyclerViewSetting() called") 174 | 175 | this.photoGridRecyeclerViewAdapter = PhotoGridRecyeclerViewAdapter() 176 | 177 | this.photoGridRecyeclerViewAdapter.submitList(photoList) 178 | 179 | my_photo_recycler_view.layoutManager = GridLayoutManager(this, 180 | 2, 181 | GridLayoutManager.VERTICAL, 182 | false) 183 | my_photo_recycler_view.adapter = this.photoGridRecyeclerViewAdapter 184 | 185 | } 186 | 187 | @FlowPreview 188 | override fun onCreateOptionsMenu(menu: Menu?): Boolean { 189 | Log.d(TAG, "PhotoCollectionActivity - onCreateOptionsMenu() called") 190 | 191 | val inflater = menuInflater 192 | 193 | inflater.inflate(R.menu.top_app_bar_menu, menu) 194 | 195 | val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager 196 | 197 | this.mySearchView = menu?.findItem(R.id.search_menu_item)?.actionView as SearchView 198 | 199 | this.mySearchView.apply { 200 | this.queryHint = "검색어를 입력해주세요" 201 | 202 | this.setOnQueryTextListener(this@PhotoCollectionActivity) 203 | 204 | this.setOnQueryTextFocusChangeListener { _, hasExpaned -> 205 | when(hasExpaned) { 206 | true -> { 207 | Log.d(TAG, "서치뷰 열림") 208 | // linear_search_history_view.visibility = View.VISIBLE 209 | 210 | handleSearchViewUi() 211 | } 212 | false -> { 213 | Log.d(TAG, "서치뷰 닫힘") 214 | linear_search_history_view.visibility = View.INVISIBLE 215 | } 216 | } 217 | } 218 | 219 | // 서치뷰에서 에딧텍스트를 가져온다. 220 | mySearchViewEditText = this.findViewById(androidx.appcompat.R.id.search_src_text) 221 | 222 | /* Rx 적용 부 223 | // 에딧텍스트 옵저버블 224 | val editTextChangeObservable = mySearchViewEditText.textChanges() 225 | 226 | val searchEditTextSubscription : Disposable = 227 | // 옵저버블에 오퍼레이터들 추가 228 | editTextChangeObservable 229 | // 글자가 입력 되고 나서 0.8 초 후에 onNext 이벤트로 데이터 흘려보내기 230 | .debounce(1000, TimeUnit.MILLISECONDS) 231 | // IO 쓰레드에서 돌리겠다. 232 | // Scheduler instance intended for IO-bound work. 233 | // 네트워크 요청, 파일 읽기,쓰기, 디비처리 등 234 | .subscribeOn(Schedulers.io()) 235 | // 구독을 통해 이벤트 응답 받기 236 | .subscribeBy( 237 | onNext = { 238 | Log.d("RX", "onNext : $it") 239 | //TODO:: 흘러들어온 이벤트 데이터로 api 호출 240 | if (it.isNotEmpty()){ 241 | searchPhotoApiCall(it.toString()) 242 | } 243 | }, 244 | onComplete = { 245 | Log.d("RX", "onComplete") 246 | }, 247 | onError = { 248 | Log.d("RX", "onError : $it") 249 | } 250 | ) 251 | // compositeDisposable 에 추가 252 | myCompositeDisposable.add(searchEditTextSubscription) 253 | */ 254 | 255 | // Rx의 스케줄러와 비슷 256 | // IO 스레드에서 돌리겠다 257 | GlobalScope.launch(context = myCoroutineContext){ 258 | 259 | // editText 가 변경되었을때 260 | val editTextFlow = mySearchViewEditText.textChangesToFlow() 261 | 262 | editTextFlow 263 | // 연산자들 264 | // 입려되고 나서 2초 뒤에 받는다 265 | .debounce(2000) 266 | .filter { 267 | it?.length!! > 0 268 | } 269 | .onEach { 270 | Log.d(TAG, "flow로 받는다 $it") 271 | // 해당 검색어로 api 호출 272 | searchPhotoApiCall(it.toString()) 273 | } 274 | .launchIn(this) 275 | } 276 | 277 | 278 | } 279 | 280 | 281 | 282 | this.mySearchViewEditText.apply { 283 | this.filters = arrayOf(InputFilter.LengthFilter(12)) 284 | this.setTextColor(Color.WHITE) 285 | this.setHintTextColor(Color.WHITE) 286 | } 287 | 288 | 289 | return true 290 | } 291 | 292 | 293 | // 서치뷰 검색어 입력 이벤트 294 | // 검색버튼이 클릭되었을때 295 | override fun onQueryTextSubmit(query: String?): Boolean { 296 | 297 | Log.d(TAG, "PhotoCollectionActivity - onQueryTextSubmit() called / query: $query") 298 | 299 | 300 | if(!query.isNullOrEmpty()){ 301 | this.top_app_bar.title = query 302 | 303 | //TODO:: api 호출 304 | //TODO:: 검색어 저장 305 | this.insertSearchTermHistory(query) 306 | this.searchPhotoApiCall(query) 307 | } 308 | 309 | // this.mySearchView.setQuery("", false) 310 | // this.mySearchView.clearFocus() 311 | 312 | this.top_app_bar.collapseActionView() 313 | 314 | return true 315 | } 316 | 317 | override fun onQueryTextChange(newText: String?): Boolean { 318 | Log.d(TAG, "PhotoCollectionActivity - onQueryTextChange() called / newText: $newText") 319 | 320 | // val userInputText = newText ?: "" 321 | 322 | val userInputText = newText.let { 323 | it 324 | }?: "" 325 | 326 | if(userInputText.count() == 12){ 327 | Toast.makeText(this, "검색어는 12자 까지만 입력 가능합니다.", Toast.LENGTH_SHORT).show() 328 | } 329 | 330 | // if(userInputText.length in 1..12){ 331 | // searchPhotoApiCall(userInputText) 332 | // } 333 | 334 | return true 335 | } 336 | 337 | 338 | override fun onCheckedChanged(switch: CompoundButton?, isChecked: Boolean) { 339 | when(switch){ 340 | search_history_mode_switch ->{ 341 | if(isChecked == true){ 342 | Log.d(TAG, "검색어 저장기능 온") 343 | SharedPrefManager.setSearchHistoryMode(isActivated = true) 344 | } else { 345 | Log.d(TAG, "검색어 저장기능 오프") 346 | SharedPrefManager.setSearchHistoryMode(isActivated = false) 347 | } 348 | } 349 | 350 | } 351 | } 352 | 353 | override fun onClick(view: View?) { 354 | when(view){ 355 | clear_search_history_buttton -> { 356 | Log.d(TAG, "검색 기록 삭제 버튼이 클릭 되었다.") 357 | SharedPrefManager.clearSearchHistoryList() 358 | this.searchHistoryList.clear() 359 | // ui 처리 360 | handleSearchViewUi() 361 | } 362 | } 363 | } 364 | 365 | // 검색 아이템삭제 버튼 이벤트 366 | override fun onSearchItemDeleteClicked(position: Int) { 367 | Log.d(TAG, "PhotoCollectionActivity - onSearchItemDeleteClicked() called / position: $position") 368 | // 해당 요소 삭제 369 | this.searchHistoryList.removeAt(position) 370 | // 데이터 덮어쓰기 371 | SharedPrefManager.storeSearchHistoryList(this.searchHistoryList) 372 | // 데이터 변경 됬다고 알려줌 373 | this.mySearchHistoryRecyclerViewAdapter.notifyDataSetChanged() 374 | 375 | handleSearchViewUi() 376 | } 377 | 378 | // 검색 아이템 버튼 이벤트 379 | override fun onSearchItemClicked(position: Int) { 380 | Log.d(TAG, "PhotoCollectionActivity - onSearchItemClicked() called / position: $position") 381 | // TODO:: 해당 녀석의 검색어로 API 호출 382 | 383 | val queryString = this.searchHistoryList[position].term 384 | 385 | searchPhotoApiCall(queryString) 386 | 387 | top_app_bar.title = queryString 388 | 389 | this.insertSearchTermHistory(searchTerm = queryString) 390 | 391 | this.top_app_bar.collapseActionView() 392 | 393 | 394 | } 395 | 396 | 397 | // 사진 검색 API 호출 398 | private fun searchPhotoApiCall(query: String){ 399 | 400 | RetrofitManager.instance.searchPhotos(searchTerm = query, completion = { status, list -> 401 | when(status){ 402 | RESPONSE_STATUS.OKAY -> { 403 | Log.d(TAG, "PhotoCollectionActivity - searchPhotoApiCall() called 응답 성공 / list.size : ${list?.size}") 404 | 405 | if (list != null){ 406 | this.photoList.clear() 407 | this.photoList = list 408 | this.photoGridRecyeclerViewAdapter.submitList(this.photoList) 409 | this.photoGridRecyeclerViewAdapter.notifyDataSetChanged() 410 | } 411 | 412 | } 413 | RESPONSE_STATUS.NO_CONTENT -> { 414 | Toast.makeText(this, "$query 에 대한 검색 결과가 없습니다.", Toast.LENGTH_SHORT).show() 415 | } 416 | } 417 | }) 418 | 419 | } 420 | 421 | 422 | private fun handleSearchViewUi(){ 423 | Log.d(TAG, "PhotoCollectionActivity - handleSearchViewUi() called / size : ${this.searchHistoryList.size}") 424 | 425 | if(this.searchHistoryList.size > 0){ 426 | search_history_recycler_view.visibility = View.VISIBLE 427 | search_history_recycler_view_label.visibility = View.VISIBLE 428 | clear_search_history_buttton.visibility = View.VISIBLE 429 | } else { 430 | search_history_recycler_view.visibility = View.INVISIBLE 431 | search_history_recycler_view_label.visibility = View.INVISIBLE 432 | clear_search_history_buttton.visibility = View.INVISIBLE 433 | } 434 | 435 | } 436 | 437 | // 검색어 저장 438 | private fun insertSearchTermHistory(searchTerm: String){ 439 | Log.d(TAG, "PhotoCollectionActivity - insertSearchTermHistory() called") 440 | 441 | if(SharedPrefManager.checkSearchHistoryMode() == true){ 442 | // 중복 아이템 삭제 443 | var indexListToRemove = ArrayList() 444 | 445 | this.searchHistoryList.forEachIndexed{ index, searchDataItem -> 446 | 447 | if(searchDataItem.term == searchTerm){ 448 | Log.d(TAG, "index: $index") 449 | indexListToRemove.add(index) 450 | } 451 | } 452 | 453 | indexListToRemove.forEach { 454 | this.searchHistoryList.removeAt(it) 455 | } 456 | 457 | // 새 아이템 넣기 458 | val newSearchData = SearchData(term = searchTerm, timestamp = Date().toSimpleString()) 459 | this.searchHistoryList.add(newSearchData) 460 | 461 | // 기존 데이터에 덮어쓰기 462 | SharedPrefManager.storeSearchHistoryList(this.searchHistoryList) 463 | 464 | this.mySearchHistoryRecyclerViewAdapter.notifyDataSetChanged() 465 | } 466 | 467 | } 468 | 469 | 470 | } 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/model/Photo.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.model 2 | 3 | import java.io.Serializable 4 | 5 | data class Photo(var thumbnail: String?, 6 | var author: String?, 7 | var createdAt: String?, 8 | var likesCount: Int?) :Serializable { 9 | } 10 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/model/SearchData.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.model 2 | 3 | data class SearchData(val timestamp: String, val term: String){ 4 | 5 | } 6 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/recyclerview/ISearchHistoryRecyclerView.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.recyclerview 2 | 3 | interface ISearchHistoryRecyclerView { 4 | 5 | // 검색 아이템 삭제 버튼 클릭 6 | fun onSearchItemDeleteClicked(position: Int) 7 | 8 | // 검색 버튼 클릭 9 | fun onSearchItemClicked(position: Int) 10 | 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/recyclerview/PhotoGridRecyeclerViewAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.recyclerview 2 | 3 | import android.view.LayoutInflater 4 | import android.view.ViewGroup 5 | import androidx.recyclerview.widget.RecyclerView 6 | import com.jeongdaeri.unsplash_app_tutorial.App 7 | import com.jeongdaeri.unsplash_app_tutorial.R 8 | import com.jeongdaeri.unsplash_app_tutorial.model.Photo 9 | 10 | 11 | //class PhotoGridRecyeclerViewAdapter(photoList: ArrayList) : RecyclerView.Adapter(){ 12 | 13 | class PhotoGridRecyeclerViewAdapter : RecyclerView.Adapter(){ 14 | 15 | 16 | private var photoList = ArrayList() 17 | 18 | // 뷰홀더와 레이아웃 연결 19 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoItemViewHolder { 20 | 21 | val photoItemViewHolder = PhotoItemViewHolder(LayoutInflater 22 | .from(parent.context) 23 | .inflate(R.layout.layout_photo_item, parent, false)) 24 | 25 | return photoItemViewHolder 26 | } 27 | 28 | // 보여줄 목록의 갯수 29 | override fun getItemCount(): Int { 30 | return this.photoList.size 31 | } 32 | 33 | // 뷰가 묶였을때 데이터를 뷰홀더에 넘겨준다. 34 | override fun onBindViewHolder(holder: PhotoItemViewHolder, position: Int) { 35 | 36 | holder.bindWithView(this.photoList[position]) 37 | 38 | } 39 | 40 | 41 | // 외부에서 어답터에 데이터 배열을 넣어준다. 42 | fun submitList(photoList: ArrayList){ 43 | this.photoList = photoList 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/recyclerview/PhotoItemViewHolder.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.recyclerview 2 | 3 | import android.util.Log 4 | import android.view.View 5 | import androidx.recyclerview.widget.RecyclerView 6 | import com.bumptech.glide.Glide 7 | import com.jeongdaeri.unsplash_app_tutorial.App 8 | import com.jeongdaeri.unsplash_app_tutorial.R 9 | import com.jeongdaeri.unsplash_app_tutorial.model.Photo 10 | import com.jeongdaeri.unsplash_app_tutorial.utils.Constants.TAG 11 | import kotlinx.android.synthetic.main.layout_photo_item.view.* 12 | 13 | 14 | class PhotoItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { 15 | 16 | 17 | // 뷰들을 가져온다. 18 | private val photoImageView = itemView.photo_image 19 | private val photoCreatedAtText = itemView.created_at_text 20 | private val photoLikesCountText = itemView.likes_count_text 21 | 22 | 23 | // 데이터와 뷰를 묶는다. 24 | fun bindWithView(photoItem: Photo){ 25 | Log.d(TAG, "PhotoItemViewHolder - bindWithView() called") 26 | 27 | photoCreatedAtText.text = photoItem.createdAt 28 | 29 | photoLikesCountText.text = photoItem.likesCount.toString() 30 | 31 | // 이미지를 설정한다. 32 | Glide.with(App.instance) 33 | .load(photoItem.thumbnail) 34 | .placeholder(R.drawable.ic_baseline_insert_photo_24) 35 | .into(photoImageView) 36 | 37 | 38 | } 39 | 40 | 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/recyclerview/SearchHistoryRecyclerViewAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.recyclerview 2 | 3 | import android.util.Log 4 | import android.view.LayoutInflater 5 | import android.view.ViewGroup 6 | import androidx.recyclerview.widget.RecyclerView 7 | import com.jeongdaeri.unsplash_app_tutorial.R 8 | import com.jeongdaeri.unsplash_app_tutorial.model.Photo 9 | import com.jeongdaeri.unsplash_app_tutorial.model.SearchData 10 | import com.jeongdaeri.unsplash_app_tutorial.utils.Constants.TAG 11 | 12 | class SearchHistoryRecyclerViewAdapter(searchHistoryRecyclerViewInterface: ISearchHistoryRecyclerView) 13 | : RecyclerView.Adapter() 14 | { 15 | 16 | 17 | private var searchHistoryList: ArrayList = ArrayList() 18 | 19 | private var iSearchHistoryRecyclerView : ISearchHistoryRecyclerView? = null 20 | 21 | init { 22 | Log.d(TAG, "SearchHistoryRecyclerViewAdapter - init() called") 23 | this.iSearchHistoryRecyclerView = searchHistoryRecyclerViewInterface 24 | } 25 | 26 | 27 | // 뷰홀더가 메모리에 올라갔을때 28 | // 뷰홀더와 레이아웃을 연결 시켜준다. 29 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchItemViewHolder { 30 | val searchItemViewHolder = SearchItemViewHolder( 31 | LayoutInflater 32 | .from(parent.context) 33 | .inflate(R.layout.layout_search_item, parent, false) 34 | , this.iSearchHistoryRecyclerView!! 35 | ) 36 | 37 | return searchItemViewHolder 38 | } 39 | 40 | 41 | override fun getItemCount(): Int { 42 | return searchHistoryList.size 43 | } 44 | 45 | 46 | override fun onBindViewHolder(holder: SearchItemViewHolder, position: Int) { 47 | 48 | val dataItem: SearchData = this.searchHistoryList[position] 49 | 50 | holder.bindWithView(dataItem) 51 | 52 | } 53 | 54 | // 외부에서 어답터에 데이터 배열을 넣어준다. 55 | fun submitList(searchHistoryList: ArrayList){ 56 | this.searchHistoryList = searchHistoryList 57 | } 58 | 59 | 60 | } 61 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/recyclerview/SearchItemViewHolder.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.recyclerview 2 | 3 | import android.util.Log 4 | import android.view.View 5 | import androidx.recyclerview.widget.RecyclerView 6 | import com.jeongdaeri.unsplash_app_tutorial.model.SearchData 7 | import com.jeongdaeri.unsplash_app_tutorial.utils.Constants.TAG 8 | import kotlinx.android.synthetic.main.layout_search_item.view.* 9 | import java.util.* 10 | 11 | class SearchItemViewHolder(itemView: View, 12 | searchRecyclerViewInterface: ISearchHistoryRecyclerView) 13 | : RecyclerView.ViewHolder(itemView), 14 | View.OnClickListener 15 | { 16 | 17 | private var mySearchRecyclerViewInterface: ISearchHistoryRecyclerView 18 | 19 | // 뷰 가져오기 20 | private val searchTermTextView = itemView.search_term_text 21 | private val whenSearchedTextView = itemView.when_searched_text 22 | private val deleteSearchBtn = itemView.delete_search_btn 23 | private val constraintSearchItem = itemView.constraint_search_item 24 | 25 | init { 26 | Log.d(TAG, "SearchItemViewHolder - init() called") 27 | // 리스너 연결 28 | deleteSearchBtn.setOnClickListener(this) 29 | constraintSearchItem.setOnClickListener(this) 30 | this.mySearchRecyclerViewInterface = searchRecyclerViewInterface 31 | } 32 | 33 | // 데이터와 뷰를 묶는다. 34 | fun bindWithView(searchItem: SearchData){ 35 | Log.d(TAG, "SearchItemViewHolder - bindWithView() called") 36 | 37 | whenSearchedTextView.text = searchItem.timestamp 38 | 39 | searchTermTextView.text = searchItem.term 40 | 41 | } 42 | 43 | override fun onClick(view: View?) { 44 | Log.d(TAG, "SearchItemViewHolder - onClick() called") 45 | when(view){ 46 | deleteSearchBtn -> { 47 | Log.d(TAG, "SearchItemViewHolder - 검색 삭제 버튼 클릭") 48 | this.mySearchRecyclerViewInterface.onSearchItemDeleteClicked(adapterPosition) 49 | } 50 | constraintSearchItem -> { 51 | Log.d(TAG, "SearchItemViewHolder - 검색 아이템 클릭") 52 | this.mySearchRecyclerViewInterface.onSearchItemClicked(adapterPosition) 53 | } 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/retrofit/IRetrofit.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.retrofit 2 | 3 | import com.google.gson.JsonElement 4 | import com.jeongdaeri.unsplash_app_tutorial.utils.API 5 | import retrofit2.Call 6 | import retrofit2.http.GET 7 | import retrofit2.http.Query 8 | 9 | interface IRetrofit { 10 | 11 | // https://www.unsplash.com/search/photos/?query="" 12 | 13 | @GET(API.SEARCH_PHOTOS) 14 | fun searchPhotos(@Query("query") searchTerm: String) : Call 15 | 16 | @GET(API.SEARCH_USERS) 17 | fun searchUsers(@Query("query") searchTerm: String) : Call 18 | 19 | } 20 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/retrofit/RetrofitClient.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.retrofit 2 | 3 | import android.os.Handler 4 | import android.os.Looper 5 | import android.util.Log 6 | import android.widget.Toast 7 | import com.jeongdaeri.unsplash_app_tutorial.App 8 | import com.jeongdaeri.unsplash_app_tutorial.utils.API 9 | import com.jeongdaeri.unsplash_app_tutorial.utils.Constants.TAG 10 | import com.jeongdaeri.unsplash_app_tutorial.utils.isJsonArray 11 | import com.jeongdaeri.unsplash_app_tutorial.utils.isJsonObject 12 | import okhttp3.Handshake 13 | import okhttp3.Interceptor 14 | import okhttp3.OkHttpClient 15 | import okhttp3.Response 16 | import okhttp3.logging.HttpLoggingInterceptor 17 | import org.json.JSONObject 18 | import retrofit2.Retrofit 19 | import retrofit2.converter.gson.GsonConverterFactory 20 | import java.lang.Exception 21 | import java.util.concurrent.TimeUnit 22 | 23 | 24 | // 싱글턴 25 | object RetrofitClient { 26 | // 레트로핏 클라이언트 선언 27 | 28 | private var retrofitClient: Retrofit? = null 29 | // private lateinit var retrofitClient: Retrofit 30 | 31 | 32 | // 레트로핏 클라이언트 가져오기 33 | fun getClient(baseUrl: String): Retrofit? { 34 | Log.d(TAG, "RetrofitClient - getClient() called") 35 | 36 | // okhttp 인스턴스 생성 37 | val client = OkHttpClient.Builder() 38 | 39 | // 로그를 찍기 위해 로깅 인터셉터 설정 40 | val loggingInterceptor = HttpLoggingInterceptor(object: HttpLoggingInterceptor.Logger{ 41 | 42 | override fun log(message: String) { 43 | // Log.d(TAG, "RetrofitClient - log() called / message: $message") 44 | 45 | when { 46 | message.isJsonObject() -> 47 | Log.d(TAG, JSONObject(message).toString(4)) 48 | message.isJsonArray() -> 49 | Log.d(TAG, JSONObject(message).toString(4)) 50 | else -> { 51 | try { 52 | Log.d(TAG, JSONObject(message).toString(4)) 53 | } catch (e: Exception) { 54 | Log.d(TAG, message) 55 | } 56 | } 57 | } 58 | 59 | } 60 | 61 | }) 62 | 63 | loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY) 64 | 65 | // 위에서 설정한 로깅 인터셉터를 okhttp 클라이언트에 추가한다. 66 | client.addInterceptor(loggingInterceptor) 67 | 68 | 69 | // 기본 파라매터 인터셉터 설정 70 | val baseParameterInterceptor : Interceptor = (object : Interceptor{ 71 | 72 | override fun intercept(chain: Interceptor.Chain): Response { 73 | Log.d(TAG, "RetrofitClient - intercept() called") 74 | // 오리지날 리퀘스트 75 | val originalRequest = chain.request() 76 | 77 | // ?client_id=asdfadsf 78 | // 쿼리 파라매터 추가하기 79 | val addedUrl = originalRequest.url.newBuilder().addQueryParameter("client_id", API.CLIENT_ID).build() 80 | 81 | val finalRequest = originalRequest.newBuilder() 82 | .url(addedUrl) 83 | .method(originalRequest.method, originalRequest.body) 84 | .build() 85 | 86 | 87 | val response = chain.proceed(finalRequest) 88 | 89 | if(response.code != 200) { 90 | 91 | Handler(Looper.getMainLooper()).post { 92 | Toast.makeText(App.instance, "${response.code} 에러 입니다.", Toast.LENGTH_SHORT).show() 93 | } 94 | 95 | } 96 | 97 | return response 98 | 99 | } 100 | 101 | }) 102 | 103 | 104 | // 위에서 설정한 기본파라매터 인터셉터를 okhttp 클라이언트에 추가한다. 105 | client.addInterceptor(baseParameterInterceptor) 106 | 107 | // 커넥션 타임아웃 108 | client.connectTimeout(10, TimeUnit.SECONDS) 109 | client.readTimeout(10, TimeUnit.SECONDS) 110 | client.writeTimeout(10, TimeUnit.SECONDS) 111 | client.retryOnConnectionFailure(true) 112 | 113 | 114 | if(retrofitClient == null){ 115 | 116 | // 레트로핏 빌더를 통해 인스턴스 생성 117 | retrofitClient = Retrofit.Builder() 118 | .baseUrl(baseUrl) 119 | .addConverterFactory(GsonConverterFactory.create()) 120 | 121 | // 위에서 설정한 클라이언트로 레트로핏 클라이언트를 설정한다. 122 | .client(client.build()) 123 | 124 | .build() 125 | } 126 | 127 | return retrofitClient 128 | } 129 | 130 | 131 | } 132 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/retrofit/RetrofitManager.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.retrofit 2 | 3 | import android.util.Log 4 | import com.google.gson.JsonElement 5 | import com.jeongdaeri.unsplash_app_tutorial.model.Photo 6 | import com.jeongdaeri.unsplash_app_tutorial.utils.API 7 | import com.jeongdaeri.unsplash_app_tutorial.utils.Constants.TAG 8 | import com.jeongdaeri.unsplash_app_tutorial.utils.RESPONSE_STATUS 9 | import retrofit2.Call 10 | import retrofit2.Response 11 | import java.text.SimpleDateFormat 12 | 13 | class RetrofitManager { 14 | 15 | companion object { 16 | val instance = RetrofitManager() 17 | } 18 | 19 | // 레트로핏 인터페이스 가져오기 20 | private val iRetrofit : IRetrofit? = RetrofitClient.getClient(API.BASE_URL)?.create(IRetrofit::class.java) 21 | 22 | 23 | // 사진 검색 api 호출 24 | fun searchPhotos(searchTerm: String?, completion: (RESPONSE_STATUS, ArrayList?) -> Unit){ 25 | 26 | val term = searchTerm.let { 27 | it 28 | }?: "" 29 | 30 | // val term = searchTerm ?: "" 31 | 32 | val call = iRetrofit?.searchPhotos(searchTerm = term).let { 33 | it 34 | }?: return 35 | // val call = iRetrofit?.searchPhotos(searchTerm = term) ?: return 36 | 37 | call.enqueue(object : retrofit2.Callback{ 38 | 39 | // 응답 실패시 40 | override fun onFailure(call: Call, t: Throwable) { 41 | Log.d(TAG, "RetrofitManager - onFailure() called / t: $t") 42 | 43 | completion(RESPONSE_STATUS.FAIL, null) 44 | 45 | } 46 | 47 | // 응답 성공시 48 | override fun onResponse(call: Call, response: Response) { 49 | Log.d(TAG, "RetrofitManager - onResponse() called / response : ${response.body()}") 50 | 51 | 52 | when(response.code()){ 53 | 200 -> { 54 | 55 | response.body()?.let { 56 | 57 | var parsedPhotoDataArray = ArrayList() 58 | 59 | val body = it.asJsonObject 60 | 61 | val results = body.getAsJsonArray("results") 62 | 63 | val total = body.get("total").asInt 64 | 65 | Log.d(TAG, "RetrofitManager - onResponse() called / total: $total") 66 | 67 | // 데이터가 없으면 no_content 로 보낸다. 68 | if(total == 0) { 69 | completion(RESPONSE_STATUS.NO_CONTENT, null) 70 | 71 | } else { // 데이터가 있다면 72 | 73 | results.forEach { resultItem -> 74 | val resultItemObject = resultItem.asJsonObject 75 | val user = resultItemObject.get("user").asJsonObject 76 | val username : String = user.get("username").asString 77 | val likesCount = resultItemObject.get("likes").asInt 78 | val thumbnailLink = resultItemObject.get("urls").asJsonObject.get("thumb").asString 79 | val createdAt = resultItemObject.get("created_at").asString 80 | val parser = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") 81 | val formatter = SimpleDateFormat("yyyy년\nMM월 dd일") 82 | 83 | val outputDateString = formatter.format(parser.parse(createdAt)) 84 | 85 | // Log.d(TAG, "RetrofitManager - outputDateString : $outputDateString") 86 | 87 | val photoItem = Photo( 88 | author = username, 89 | likesCount = likesCount, 90 | thumbnail = thumbnailLink, 91 | createdAt = outputDateString 92 | ) 93 | parsedPhotoDataArray.add(photoItem) 94 | 95 | } 96 | 97 | completion(RESPONSE_STATUS.OKAY , parsedPhotoDataArray) 98 | } 99 | } 100 | 101 | 102 | } 103 | } 104 | 105 | 106 | 107 | } 108 | 109 | }) 110 | } 111 | 112 | 113 | } 114 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/utils/Constants.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.utils 2 | 3 | object Constants { 4 | const val TAG : String = "로그" 5 | } 6 | 7 | enum class SEARCH_TYPE { 8 | PHOTO, 9 | USER 10 | } 11 | 12 | enum class RESPONSE_STATUS { 13 | OKAY, 14 | FAIL, 15 | NO_CONTENT 16 | } 17 | 18 | 19 | object API { 20 | const val BASE_URL : String = "https://api.unsplash.com/" 21 | 22 | // 여러분꺼 하셔야됩니다!! ㅎㅎ;; 23 | const val CLIENT_ID : String = "YS7sdqX2kuYBOifsupK1A-J2S4tkMveczqAQVOEBJMs" 24 | 25 | const val SEARCH_PHOTOS : String = "search/photos" 26 | const val SEARCH_USERS : String = "search/users" 27 | 28 | } 29 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/utils/Extensions.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.utils 2 | 3 | import android.text.Editable 4 | import android.text.TextWatcher 5 | import android.util.Log 6 | import android.widget.EditText 7 | import com.jeongdaeri.unsplash_app_tutorial.utils.Constants.TAG 8 | import kotlinx.coroutines.ExperimentalCoroutinesApi 9 | import kotlinx.coroutines.channels.awaitClose 10 | import kotlinx.coroutines.flow.Flow 11 | import kotlinx.coroutines.flow.callbackFlow 12 | import kotlinx.coroutines.flow.onStart 13 | import java.text.SimpleDateFormat 14 | import java.util.* 15 | 16 | 17 | // 문자열이 제이슨 형태인지 18 | fun String?.isJsonObject():Boolean { 19 | if(this?.startsWith("{") == true && this.endsWith("}")){ 20 | return true 21 | } else { 22 | return false 23 | } 24 | // return this?.startsWith("{") == true && this.endsWith("}") 25 | } 26 | //fun String?.isJsonObject():Boolean = this?.startsWith("{") == true && this.endsWith("}") 27 | 28 | // 문자열이 제이슨 배열인지 29 | fun String?.isJsonArray() : Boolean { 30 | if(this?.startsWith("[") == true && this.endsWith("]")){ 31 | return true 32 | } else { 33 | return false 34 | } 35 | } 36 | 37 | 38 | // 날짜 포맷 39 | fun Date.toSimpleString() : String { 40 | val format = SimpleDateFormat("HH:mm:ss") 41 | return format.format(this) 42 | } 43 | 44 | 45 | 46 | // 에딧 텍스트에 대한 익스텐션 47 | fun EditText.onMyTextChanged(completion: (Editable?) -> Unit){ 48 | this.addTextChangedListener(object: TextWatcher { 49 | 50 | override fun afterTextChanged(editable: Editable?) { 51 | completion(editable) 52 | } 53 | 54 | override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { 55 | 56 | } 57 | 58 | override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { 59 | 60 | } 61 | 62 | }) 63 | } 64 | 65 | // 에딧텍스트 텍스트 변경을 flow로 받기 66 | @ExperimentalCoroutinesApi 67 | fun EditText.textChangesToFlow(): Flow { 68 | 69 | // flow 콜백 받기 70 | return callbackFlow { 71 | 72 | val listener = object : TextWatcher { 73 | override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit 74 | 75 | override fun afterTextChanged(p0: Editable?) { 76 | Unit 77 | } 78 | 79 | override fun onTextChanged(text: CharSequence?, p1: Int, p2: Int, p3: Int) { 80 | Log.d(TAG, "onTextChanged() / textChangesToFlow() 에 달려있는 텍스트 와쳐 / text : $text") 81 | // 값 내보내기 82 | offer(text) 83 | } 84 | } 85 | // 위에서 설정한 리스너 달아주기 86 | addTextChangedListener(listener) 87 | 88 | // 콜백이 사라질때 실행됨 89 | awaitClose { 90 | Log.d(TAG, "textChangesToFlow() awaitClose 실행") 91 | removeTextChangedListener(listener) 92 | } 93 | 94 | }.onStart { 95 | Log.d(TAG, "textChangesToFlow() / onStart 발동") 96 | // Rx 에서 onNext 와 동일 97 | // emit 으로 이벤트를 전달 98 | emit(text) 99 | } 100 | 101 | } 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /app/src/main/java/com/jeongdaeri/unsplash_app_tutorial/utils/SharedPrefManager.kt: -------------------------------------------------------------------------------- 1 | package com.jeongdaeri.unsplash_app_tutorial.utils 2 | 3 | import android.content.Context 4 | import android.util.Log 5 | import com.google.gson.Gson 6 | import com.jeongdaeri.unsplash_app_tutorial.App 7 | import com.jeongdaeri.unsplash_app_tutorial.model.SearchData 8 | import com.jeongdaeri.unsplash_app_tutorial.utils.Constants.TAG 9 | 10 | object SharedPrefManager { 11 | 12 | private const val SHARED_SHEARCH_HISTORY = "shared_search_history" 13 | private const val KEY_SEARCH_HISTORY = "key_search_history" 14 | 15 | private const val SHARED_SEARCH_HISTORY_MODE = "shared_search_history_mode" 16 | private const val KEY_SEARCH_HISTORY_MODE = "key_search_history_mode" 17 | 18 | // 검색어 저장 모드 설정하기 19 | fun setSearchHistoryMode(isActivated: Boolean){ 20 | Log.d(TAG, "SharedPrefManager - setSearchHistoryMode() called / isActivated: $isActivated") 21 | 22 | // 쉐어드 가져오기 23 | val shared = App.instance.getSharedPreferences(SHARED_SEARCH_HISTORY_MODE, Context.MODE_PRIVATE) 24 | 25 | // 쉐어드 에디터 가져오기 26 | val editor = shared.edit() 27 | 28 | editor.putBoolean(KEY_SEARCH_HISTORY_MODE, isActivated) 29 | 30 | editor.apply() 31 | 32 | } 33 | 34 | 35 | // 검색어 저장 모드 확인하기 36 | fun checkSearchHistoryMode() : Boolean { 37 | 38 | // 쉐어드 가져오기 39 | val shared = App.instance.getSharedPreferences(SHARED_SEARCH_HISTORY_MODE, Context.MODE_PRIVATE) 40 | 41 | return shared.getBoolean(KEY_SEARCH_HISTORY_MODE, false) 42 | } 43 | 44 | 45 | // 검색 목록을 저장 46 | fun storeSearchHistoryList(searchHistoryList: MutableList){ 47 | Log.d(TAG, "SharedPrefManager - storeSearchHistoryList() called") 48 | 49 | // 매개변수로 들어온 배열을 -> 문자열로 변환 50 | val searchHistoryListString : String = Gson().toJson(searchHistoryList) 51 | Log.d(TAG, "SharedPrefManager - searchHistoryListString : $searchHistoryListString") 52 | 53 | // 쉐어드 가져오기 54 | val shared = App.instance.getSharedPreferences(SHARED_SHEARCH_HISTORY, Context.MODE_PRIVATE) 55 | 56 | // 쉐어드 에디터 가져오기 57 | val editor = shared.edit() 58 | 59 | editor.putString(KEY_SEARCH_HISTORY, searchHistoryListString) 60 | 61 | editor.apply() 62 | 63 | } 64 | 65 | // 검색 목록 가져오기 66 | fun getSearchHistoryList() : MutableList { 67 | 68 | // 쉐어드 가져오기 69 | val shared = App.instance.getSharedPreferences(SHARED_SHEARCH_HISTORY, Context.MODE_PRIVATE) 70 | 71 | val storedSearchHistoryListString = shared.getString(KEY_SEARCH_HISTORY, "")!! 72 | 73 | 74 | var storedSearchHistoryList = ArrayList() 75 | 76 | // 검색 목록이 값이 있다면 77 | if (storedSearchHistoryListString.isNotEmpty()){ 78 | 79 | // 저장된 문자열을 -> 객체 배열로 변경 80 | storedSearchHistoryList = Gson(). 81 | fromJson(storedSearchHistoryListString, Array::class.java). 82 | toMutableList() as ArrayList 83 | } 84 | 85 | return storedSearchHistoryList 86 | } 87 | 88 | // 검색 목록 지우기 89 | fun clearSearchHistoryList(){ 90 | Log.d(TAG, "SharedPrefManager - clearSearchHistoryList() called") 91 | // 쉐어드 가져오기 92 | val shared = App.instance.getSharedPreferences(SHARED_SHEARCH_HISTORY, Context.MODE_PRIVATE) 93 | 94 | // 쉐어드 에디터 가져오기 95 | val editor = shared.edit() 96 | 97 | // 해당 데이터 지우기 98 | editor.clear() 99 | 100 | // 변경 사항 적용 101 | editor.apply() 102 | } 103 | 104 | 105 | } 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | 31 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_add_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_cancel_24.xml: -------------------------------------------------------------------------------- 1 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_delete_outline_24.xml: -------------------------------------------------------------------------------- 1 | 7 | 10 | 11 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_favorite_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_insert_photo_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_menu_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_more_vert_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_baseline_search_24.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_person_black_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_photo_library_black_24dp.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_unsplash.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/rounded_bg_gray.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/rounded_bg_pink.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 19 | 20 | 27 | 33 | 43 | 52 | 53 | 54 | 69 | 70 | 78 | 79 | 80 | 81 | 82 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_photo_collection.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 15 | 16 | 26 | 27 | 28 | 29 | 35 | 36 | 37 | 46 | 51 | 60 | 71 |