inflearn logo
강의

Khóa học

Chia sẻ kiến thức

findViewById 함수 호출 시 null값 반환

1086

CNKGH

3 câu hỏi đã được viết

0

안녕하세요.  CustomAdapter 강의 수강중에 다음과 같은 에러가 발생해서 문의드립니다.

 

그대로 따라하면서 진행하였는데 이상하다 싶어서 에러 메시지를 확인해보니, 아래 코드에서 rowtextview1 변수에 null이 반환되고 있음을 확인하였습니다.

val rowtextview1 = findViewById<TextView>(R.id.rowtextView1)

 

전체 코드는 아래와 같습니다. 어떻게하면 View의 id값을 정상적으로 가져올 수 있을까요??

* MainActivity.kt *

package com.example.customadapter

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.TextView

class MainActivity : AppCompatActivity() {
val data1 = arrayOf("데이터1","데이터2","데이터3","데이터4","데이터5")

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val textveiw1 = findViewById<TextView>(R.id.textView1)
val listveiw1 = findViewById<ListView>(R.id.list1)

listveiw1.adapter = adapter1

}

//getCount의 리턴 값 만큼 getView가 호출되어 R.layout.row View 객체를 붙여준다.
val adapter1 = object : BaseAdapter(){
// 항목의 개수를 반환
override fun getCount(): Int {
return data1.size
}
// 항목의 인덱스 번호를 전달했을 때, 객체를 넘기는 기능
override fun getItem(position: Int): Any? {
return null
}
// 임의로 정해진 아이디 값을 넘겨주는 기능
override fun getItemId(position: Int): Long {
return 0
}
// 현재 화면에 표시되는 항목만큼 호출됨
// position : 몇 번째 항목을 구성할 것인가, convertView : 화면에서 없어진 뷰를 저장
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
// 재사용 가능한 View를 변수에 담는다.
var rowView = convertView

if(rowView == null) {
// inflate XML을 참고하여 View 객체를 생성 및 반환하는 함수
// 1번째 인자는 View 객체를 만들 때 참고하는 XML, 2번째 인자는 해당 View 객체의 상위 객체(레이아웃)\
rowView = layoutInflater.inflate(R.layout.row, null)
}

// 항목 뷰 내부에 배치되어 있는 뷰들의 주소 값을 가져온다.
val rowtextview1 = findViewById<TextView>(R.id.rowtextView1)

rowtextview1.text = data1[position]

return rowView!!
}
}
}

* activity_main.xml *

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />

<ListView
android:id="@+id/list1"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>

* row.xml *

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<TextView
android:id="@+id/rowtextView1"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_weight="1"
android:text="TextView"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />

<Button
android:id="@+id/rowbutton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="버튼1" />

<Button
android:id="@+id/rowbutton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="버튼2" />
</LinearLayout>

 

 

 

윤재성의Kotlin기반안드로이드 안드로이드 코틀린 모바일 android 코딩

Câu trả lời 1

0

hyeong keun lee


val rowtextview1 = findViewById<TextView>(R.id.rowtextView1)

이렇게 코딩 하신 부분을... 아래처럼 변경 하시면 될것같아요


val rowtextview1 = rowView.findViewById<TextView>(R.id.rowtextView1)

 

rowView. 으로 해주셔야 합니다. 

그리고 if 문 안쪽으로 넣으셔야 에러가 안나요.

(혹은 다른 부분을 수정..)

 

나중에는 ListView 대신에 RecyclerView 를 사용하시는것을 추천드려요.

6강에 비디오가 이상해요

0

27

2

진입 여부 판단 기준 질문

0

79

3

피그마 first draft 기능 질문

0

49

3

upup 질문

0

59

2

data.ai 필터링 검색이 안됩니다!

0

48

1

앱 리텐션에 대한 질문

0

50

2

저예산+최대지출 캠페인 유지시간

0

65

2

타입스크립트

0

46

1

주사위앱 소개 및 레이아웃 설정 문제

0

60

2

다작을 위한 비공개 테스트와 계정에 대해서 궁금합니다!

0

107

2

10강 오픈 일정 문의

0

89

1

개인사업자로 조직 계정을 만들 경우 이슈 질문

0

219

3

구글플레이 말고 링크로 다운로드 받는 앱은 뭔지 궁금해요

0

64

1

강의 오류

0

55

2

두 번 째 광고 게재 정지를 받았습니다 ㅠ

0

249

3

구글 애즈 광고 이미지 관련 문의

0

96

2

수업 잘 듣고 있습니다 :)

0

88

2

78강 소스코드 및 미디어 파일 미디어 파일 이미지 파일 누락

0

57

2

안드로이드 에뮬레이터가 실행이 안 되요...ㅠ

0

105

2

안녕하세요!

0

104

2

다작의 정책 위반 리스크

0

178

2

안녕하세요 ! 애드몹 광고가 게재됐다고 합니다 ..

0

143

1

애드몹 다계정 질문

0

119

1

리텐션은 좋은데 너무 낮은 ecpm

0

160

2