티스토리 뷰
https://world-of-larooly.tistory.com/51
Kotlin 연습 점심 추천 어플 만들기 2단계 목록 만들기
https://world-of-larooly.tistory.com/50 Kotlin 연습 점심 추천 어플 만들기 1단계 준비 코틀린을 공부하기 시작은 했는데 진도가 너무 안 나가는 도중에 한분이 아이디어를 주셔서 기~~~~본을 이용해서 만들
world-of-larooly.tistory.com
이번에는 드디어 점심을 추천하는 화면을 만들어보겠습니다.
(어려운 건 2단계에서 다해서 여기는 쉬워요.)
그전에 저는 추천을 그냥하면 재미없으니까 옵션을 추가해서 만들어 볼꺼에요.
* 옵션 *
1. 먹고 싶은 종류를 선택 vs 먹기 싫은 종류를 선택
2. 한식 / 일식 / 중식 / 양식&동남아 중에서 선택
3. 밥류 / 면류 / 기타류 중에서 선택
해당 옵션을 선택하는 부분은 RadioGroup으로 제작할 겁니다.
* RadioGroup
- 같은 그룹내에서 하나만 선택할수있게 해주는 버튼
이렇게 하고 옵션에 맞는 메뉴 안에서만 추천 메뉴가 나오도록 만들어볼께요.
마찬가지로 두단계에 나누어 해볼께요.
1. 화면 만들기 (activity_select.xml)
2. 코드 만들기 (SelectActivity.kt)
이번에는 어려운 부분이 없어서 쉽게 하실 수 있습니다.
1. 화면 만들기 (activity_select.xml)
- 사용자의 옵션 선택을 위해 RadioGroup 을 사용했습니다.
- 이번 화면도 이미지를 살짝 추가해서 만들었습니다.
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/mushroom_green">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="110dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent">
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="원하시는 옵션을 선택해주세요."
android:padding="10dp"
android:textColor="@color/black"
android:textSize="20sp"
android:textStyle="bold" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:gravity="center"
android:id="@+id/wantGroup"
android:orientation="horizontal">
<RadioButton
android:id="@+id/wantGroup_yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:buttonTint="@color/mushroom_pink"
android:layout_weight="1"
android:text="먹고 싶어요." />
<RadioButton
android:id="@+id/wantGroup_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="@color/mushroom_pink"
android:layout_weight="1"
android:text="먹기 싫어요." />
</RadioGroup>
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text=""먹기 싫어요" 선택시 해당 유형은 제외하고 추천드립니다."
android:textColor="@color/black"
android:textSize="16sp" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:id="@+id/kindGroup"
android:orientation="horizontal">
<RadioButton
android:id="@+id/kindGroup_ko"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="true"
android:buttonTint="@color/mushroom_pink"
android:text="한식" />
<RadioButton
android:id="@+id/kindGroup_ja"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="@color/mushroom_pink"
android:text="일식" />
<RadioButton
android:id="@+id/kindGroup_ch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="@color/mushroom_pink"
android:text="중식" />
<RadioButton
android:id="@+id/kindGroup_etc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="@color/mushroom_pink"
android:text="양식 / 동남아" />
</RadioGroup>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:id="@+id/typeGroup"
android:orientation="horizontal">
<RadioButton
android:id="@+id/typeGroup_rice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="true"
android:buttonTint="@color/mushroom_pink"
android:text="밥류" />
<RadioButton
android:id="@+id/typeGroup_noodle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="@color/mushroom_pink"
android:text="면류" />
<RadioButton
android:id="@+id/typeGroup_etc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:buttonTint="@color/mushroom_pink"
android:text="기타류" />
</RadioGroup>
<Button
android:id="@+id/startBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="@color/mushroom_pink"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:text="시작" />
<TextView
android:id="@+id/resultTv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="원하는 옵션 선택 후 시작을 눌러주세요."
android:textColor="@color/black"
android:padding="5dp"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:id="@+id/imageView2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="@drawable/cutlery" />
</androidx.constraintlayout.widget.ConstraintLayout>
2. 코드 만들기 (SelectActivity.kt)
- 마찬가지로 전체 코드 먼저 보여드릴께요.
- callMenus 는 이전 단계에서 한 것과 동일한 부분이기에 설명하지 않겠습니다. (Json -> Array로 가져오기)
package com.example.forsukquiestion
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.RadioGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.json.JSONArray
class SelectActivity : AppCompatActivity() {
//초기 설정 셋팅
var isWanted : Boolean = true // 먹고싶어요
var selectKindFood : String = "k" // 한식
var selectTypeFood : String = "r" // 밥류
var totalMenuDatas = JSONArray()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_select)
callMenus() //json에서 메뉴 가져오기
val resultLbl = findViewById<TextView>(R.id.resultTv)
val isWantedGroup = findViewById<RadioGroup>(R.id.wantGroup).setOnCheckedChangeListener { group, checkId ->
when (checkId){
R.id.wantGroup_yes -> isWanted = true
R.id.wantGroup_no -> isWanted = false
}
}
val kindGroup = findViewById<RadioGroup>(R.id.kindGroup).setOnCheckedChangeListener { group, checkId ->
when (checkId){
R.id.kindGroup_ko -> selectKindFood = "k" // 한식
R.id.kindGroup_ja -> selectKindFood = "j" // 일식
R.id.kindGroup_ch -> selectKindFood = "c" // 중식
R.id.kindGroup_etc -> selectKindFood = "a" // 양식&동남아
}
}
val typeGroup = findViewById<RadioGroup>(R.id.typeGroup).setOnCheckedChangeListener { group, checkId ->
when (checkId){
R.id.typeGroup_rice -> selectTypeFood = "r" // 밥류
R.id.typeGroup_noodle -> selectTypeFood = "n" // 면류
R.id.typeGroup_etc -> selectTypeFood = "e" // 기타류
}
}
val resultBtn = findViewById<Button>(R.id.startBtn).setOnClickListener {
resultLbl.text = getMenu(isWanted)
}
}
fun callMenus(){
val jsonName = assets.open("LunchMenu.json").reader().readText()
val lunchArray = JSONArray(jsonName)
totalMenuDatas = lunchArray
}
fun getMenu(isYes : Boolean): String{
if(isYes){
return getRandomFromArray(getYesMenu())
}else{
return getRandomFromArray(getNopeMenu())
}
}
fun getRandomFromArray(menus : Array<String>): String{
if(menus.size <= 0){
return "조건에 만족하는 음식이 없어요."
}
return menus.random()
}
//먹고 싶은 음식이름만 모아서 배열 만들기
fun getYesMenu() : Array<String>{
var resultArr = emptyArray<String>()
for (index in 0 until totalMenuDatas.length()){
val lunchPick = totalMenuDatas.getJSONObject(index)
val name = lunchPick.getString("Name")
val kind = lunchPick.getString("Kind")
val type = lunchPick.getString("Type")
if(getYesSelectBool(kind,type)){
resultArr = resultArr.plus( name)
}
}
return resultArr
}
//먹기 싫은 메뉴 제외 후 음식이름만 모아서 배열 만들기
fun getNopeMenu() : Array<String>{
var resultArr = emptyArray<String>()
for (index in 0 until totalMenuDatas.length()){
val lunchPick = totalMenuDatas.getJSONObject(index)
val name = lunchPick.getString("Name")
val kind = lunchPick.getString("Kind")
val type = lunchPick.getString("Type")
if(getNopeSelectBool(kind,type)){
resultArr = resultArr.plus( name)
}
}
return resultArr
}
fun getYesSelectBool(kind:String ,type:String) : Boolean{
// 내가 원하는 한중일/ 면밥
if(selectKindFood == kind && selectTypeFood == type){
return true
}
return false
}
fun getNopeSelectBool(kind:String ,type:String):Boolean{
// 원치 않는 한중일/ 면밥
if(selectKindFood == kind || selectTypeFood == type){
return false
}
return true
}
}
- RadioGroup 사용법은 아래처럼 써주시면 됩니다.
- 아래 함수는 여러분들이 옵션을 선택할때마다 작동하게 됩니다.
val kindGroup = findViewById<RadioGroup>(R.id.kindGroup).setOnCheckedChangeListener { group, checkId ->
when (checkId){
R.id.kindGroup_ko -> selectKindFood = "k"
R.id.kindGroup_ja -> selectKindFood = "j"
R.id.kindGroup_ch -> selectKindFood = "c"
R.id.kindGroup_etc -> selectKindFood = "a"
}
}
- 아래는 사용자의 조건에 맞는 음식이름을 배열로 만드는 함수입니다.
- 배열로 만든 후에 그중에서 랜덤으로 추천해주면 완성이겠죠?
fun getYesMenu() : Array<String>{
var resultArr = emptyArray<String>()
for (index in 0 until totalMenuDatas.length()){
val lunchPick = totalMenuDatas.getJSONObject(index)
val name = lunchPick.getString("Name")
val kind = lunchPick.getString("Kind")
val type = lunchPick.getString("Type")
if(getYesSelectBool(kind,type)){
resultArr = resultArr.plus( name)
}
}
return resultArr
}
fun getNopeMenu() : Array<String>{
var resultArr = emptyArray<String>()
for (index in 0 until totalMenuDatas.length()){
val lunchPick = totalMenuDatas.getJSONObject(index)
val name = lunchPick.getString("Name")
val kind = lunchPick.getString("Kind")
val type = lunchPick.getString("Type")
if(getNopeSelectBool(kind,type)){
resultArr = resultArr.plus( name)
}
}
return resultArr
}
fun getYesSelectBool(kind:String ,type:String) : Boolean{
// 내가 원하는 한중일/ 면밥
if(selectKindFood == kind && selectTypeFood == type){
return true
}
return false
}
fun getNopeSelectBool(kind:String ,type:String):Boolean{
if(selectKindFood == kind || selectTypeFood == type){
return false
}
return true
}
이제 여기까지 만드시면 아래처럼 보이게 됩니다.
1,2,3 단계를 순서대로 하셨다면 아래와 같은 모습의 앱이 생성되었을 겁니다.
여기까지 미니 프로젝트였습니다.
재미로 만들어본 앱인데 생각보다 기본을 다지기에 좋았던 앱인것같아서
올려봅니다.
저처럼 Kotlin을 처음 해보신 분들에게 도움이 되었으면 좋겠네요.
그럼 오늘도 파이팅입니다!
p.s.다음 포스팅에서는 아마 apk 만드는 법을 올릴것같네요.
'Android 연습 > Kotlin 익숙해지기' 카테고리의 다른 글
Kotlin 연습 Lottie / Gif로 움직이는 사진 넣기 (0) | 2023.01.22 |
---|---|
Kotlin 연습 SharedPreference (with. 앱 테마 바꾸기) (0) | 2023.01.10 |
Kotlin 연습 점심 추천 어플 만들기 2단계 목록 만들기 (0) | 2022.12.21 |
Kotlin 연습 점심 추천 어플 만들기 1단계 준비 (0) | 2022.12.16 |
Kotlin 배열 공부중 (0) | 2022.12.09 |