findViewById 함수 호출 시 null값 반환
1105
3 câu hỏi đã được viết
안녕하세요. 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>
Câu trả lời 1
0
val rowtextview1 = findViewById<TextView>(R.id.rowtextView1)
이렇게 코딩 하신 부분을... 아래처럼 변경 하시면 될것같아요
val rowtextview1 = rowView.findViewById<TextView>(R.id.rowtextView1)
rowView. 으로 해주셔야 합니다.
그리고 if 문 안쪽으로 넣으셔야 에러가 안나요.
(혹은 다른 부분을 수정..)
나중에는 ListView 대신에 RecyclerView 를 사용하시는것을 추천드려요.
보상형광고 노출율이 말도 안되게 낮습니다...
0
6
1
안드로이드 조직 계정 수익 인증 관련
0
48
2
AdMob 계정 승인이 1개월 이상 지연되고 있습니다. 앱 검토와 순서가 어떻게 되는 건가요
0
107
2
구글 플레이 API 업데이트 관련 문의
0
85
2
광고 캠페인 종류와 키워드 플래너 관련 질문
0
103
2
안드로이드 기기 실행 오류
0
72
2
테이블 컬럼에 대한 질문
0
75
1
강의에서 사용된 안드로이드 스튜디오 버전을 알고싶어요.
0
71
2
install까지 설치 하였는데 start 가안됩니다.
1
72
2
앱내 광고 빈도 관련 문의사항
0
135
2
앱 초기 진입시 전면광고 관련 질문
0
138
2
원하지 않은 외국인 유입
0
157
2
android crud중 c 영상이 12초만 있는 잘린 영상이에요.
0
79
2
6강에 비디오가 이상해요
0
75
2
진입 여부 판단 기준 질문
0
218
3
피그마 first draft 기능 질문
0
147
3
upup 질문
0
157
2
data.ai 필터링 검색이 안됩니다!
0
114
1
앱 리텐션에 대한 질문
0
129
2
저예산+최대지출 캠페인 유지시간
0
149
2
타입스크립트
0
98
1
주사위앱 소개 및 레이아웃 설정 문제
0
105
2
다작을 위한 비공개 테스트와 계정에 대해서 궁금합니다!
0
203
2
10강 오픈 일정 문의
0
147
1

