티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

findViewByID returns null

findViewByID는 null을 반환합니다.

 문제 내용 

First of all: yes, I read all the other threads on this topic. And not only those from this site... (you see, I'm a little frustrated)

우선: 네, 이 주제에 대한 다른 모든 쓰레드를 읽었습니다. 이 사이트에서만이 아니라요... (봐요, 조금 짜증이 나서요)

 

Most of them come with the advice to use android:id instead of just id in the XML file. I did.

대부분의 답변들은 XML 파일에서 `id` 대신에 `android:id`를 사용하라는 조언을 제공합니다. 그러나 제가 그렇게 했음에도 불구하고, 여전히 문제가 발생합니다.

 

From others, I learned, that View.findViewById works different than Activity.findViewById. I handled that, too.

다른 사람들의 조언으로는 XML 파일에서 `id` 대신에 `android:id`를 사용하라는 것입니다. 저는 그렇게 했습니다. 그리고 `View.findViewById`가 `Activity.findViewById`와 다르게 동작한다는 것을 배웠습니다. 그것도 처리했습니다.

 

In my location_layout.xml, I use:

저의 location_layout.xml에서는 다음과 같이 사용합니다:
<FrameLayout .... >
    <some.package.MyCustomView ... />

    <LinearLayout ... >
        <TextView ...
            android:id="@+id/txtLat" />
        ...
    </LinearLayout>
</FrameLayout>

 

In my Activity I do:

저의 액티비티에서는 다음과 같이 합니다.
...
setContentView( R.layout.location_layout );

 

and in my custom view class:

그리고 제가 만든 커스텀 뷰 클래스에서는:
... 
TextView tv = (TextView) findViewById( R.id.txtLat );

 

which returns null. Doing this, my Activity works fine. So maybe it's because of the Activity.findViewById and View.findViewById differences. So I stored the context passed to the customs view constructor locally and tried:

이렇게 하면 null을 반환합니다. 이렇게 하면 내 Activity는 잘 작동합니다. 그래서 Activity.findViewById와 View.findViewById의 차이 때문일 수 있다고 생각했습니다. 그래서 custom view 생성자에 전달된 context를 로컬로 저장하고 시도해보았습니다.
...
TextView tv = (TextView) ((Activity) context).findViewById( R.id.txtLat );

 

which also returned null.

그런데 이 방법도 null을 반환했습니다.

 

Then, I changed my custom view to extend ViewGroup instead View and changed the location_layout.xml to let the TextView be a direct child of my custom view, so that the View.findViewById should work as supposed. Suprise: it didn't solve anything.

그러면, 제가 이해하기로는, XML 파일에서 android:id 속성을 제대로 사용하고, Activity.findViewById()와 View.findViewById()가 서로 다른 방식으로 작동한다는 것도 고려하여 뷰를 찾기 위해 여러 가지 방법을 시도해 보았지만, 여전히 null을 반환한다는 말씀이신가요? 그리고 ViewGroup을 확장하는 커스텀 뷰로 변경하고 TextView를 직접적인 자식으로 가지도록 변경하여, View.findViewById가 의도한 대로 작동할 것으로 예상했지만, 여전히 문제가 해결되지 않았다는 것이 올바른 이해인가요?

 

So what the heck am I doing wrong?

그래서 제가 뭐가 잘못된 건지 모르겠습니다.

 

I'll appreciate any comments.

어떤 의견이든 감사하겠습니다.

 

 

 

 높은 점수를 받은 Solution 

which returns null

이것은 null 값을 반환합니다.

 

Possibly because you are calling it too early. Wait until onFinishInflate(). Here is a sample project demonstrating a custom View accessing its contents.

가능성 있게는 호출 시점이 너무 이른 것일 수 있습니다. onFinishInflate() 메소드까지 기다렸다가 호출해 보세요. 커스텀 View 내부의 내용물에 접근하는 방법을 보여주는 샘플 프로젝트가 있으니 참고해 보세요.

 

 

 

 가장 최근 달린 Solution 

FWIW, I don't see that anyone solved this in quite the same way as I needed to. No complaints at compile time, but I was getting a null view at runtime, and calling things in the proper order. That is, findViewById() after setContentView(). The problem turned out that my view is defined in content_main.xml, but in my activity_main.xml, I lacked this one statement:

참고로, 누구도 내가 필요로 하는 방식으로 이 문제를 해결한 것 같지는 않아요. 컴파일 시에는 아무런 문제가 없었지만 런타임에는 null view가 반환되었고, setContentView() 이후에 findViewById() 를 호출했습니다. 문제는 view가 content_main.xml에 정의되어 있지만, activity_main.xml에서 다음 문장이 누락되었다는 것이었습니다.
<include layout="@layout/content_main" />

 

When I added that to activity_main.xml, no more NullPointer.

activity_main.xml에 이 구문을 추가하니 더 이상 NullPointer 오류가 발생하지 않았습니다.

 

 

 

출처 : https://stackoverflow.com/questions/3264610/findviewbyid-returns-null

반응형
댓글
공지사항
최근에 올라온 글