• 카테고리

    질문 & 답변
  • 세부 분야

    모바일 앱 개발

  • 해결 여부

    미해결

Room db kotlin 강의중에서

24.03.10 23:59 작성 조회수 116

0

강사님 늘 건강하시고 부자되세요

 

아래 activity_main.xml 내의 요소들과 관련된 부분에서 빨간줄이 생깁니다 왜 그런지 .....

q1.png

답변 3

·

답변을 작성해보세요.

0

shafeel2님의 프로필

shafeel2

2024.03.12

일부오류는 사라졌으나

아래부분에서 오류가 발생합니다

addButton.setOnClickListener(
db.todoDao().insert(Todo(todoEdit.text.toString()))
resultText.text = db.todoDao().getAll().toString()
)

 

q2.png

TextView의 경우에 text 에 값을 지정하는 것이 안 되고 setText() 함수를 통해야 할 거에요.

resultText.setText(db.todoDao().getAll().toString()) 으로 고쳐보시겠어요?

위쪽 라인에 같은 코드도 빨간불은 없지만 아마 동일하게 수정하셔야 할 것 같습니다.

0

지금은 자동으로 XML 의 id를 가져오지 못 합니다.

따라서 Java 처럼 findViewById() 를 쓰거나, ViewBinding 이라는 걸 써야 합니다.

findViewById() 를 사용하신다면 add_button 대신에 다음과 같이 고치거나

findViewById<Button>(R.id.add_button)

사용 전에 타입에 맞도록 가져와서 미리 할당해 두어도 됩니다. (setContentView() 이후에)

val addButton = findViewById<Button>(R.id.add_button)
val todoEdit = findViewById<EditText>(R.id.todo_edit)
...

 

다른 방식으로는 ViewBinding 이라는 것이 있습니다.

findViewById() 대신에 미리 정해둔 설정을 하면 자동으로 가져다 쓸 수 있도록 하는 설정입니다.

의 가이드는 https://developer.android.com/topic/libraries/view-binding?hl=ko#kts 있습니다.

저는 ViewBinding을 선호합니다.

0

shafeel2님의 프로필

shafeel2

2024.03.11

<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">

<EditText
android:id="@+id/todo_edit"
android:hint="활동메모"
android:layout_margin="20dp"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@android:color/transparent"
tools:ignore="MissingConstraints" />


<TextView
android:id="@+id/result_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/add_button"
android:text="추가"
android:textColor="@color/white"
android:background="@color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_marginStart="160dp"
android:layout_marginTop="256dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>