본문 바로가기
mobile

Android Kotlin Only the original thread that created a view hierarchy can touch its views. Fragment 해결

by ejlee 2021. 3. 29.

이런 에러가 떴습니다 Only the original thread that created a view hierarchy can touch its views. 라더군요 ? ㅋㅋ

해석해보니 보기 계층을 생성한 원래 쓰레드만 해당 보기를 터치할 수 있습니다.  라네요.

에러 로그를 따라가다보니 이 코드가 문제인 걸 확인해버렸습니다.

단순 UI 를 수정하는 건데 뭘 그렇게 따지는지 ㅋㅋ

알고보니 UI 수정은 Main Tread 에서 해야한다더군요.

처음 겪는 에러라서 알아보는데 고생 좀 했습니다.

찾아보니 다들 Activity 를 기준으로 설명해주더군요 ㅋㅋ

runOnUiThread(Runnable() {
    override fun run() {
		binding.tvCardHomeTitle.visibility = View.GONE
 		binding.tvCardHomeTitle2.visibility = View.GONE
    }
});

정확하진 않지만 이런식으로요

 

근데

저는 Fragment 로 했습니다. Activity 랑 다르게요.

Activity 보다 더 간단하게 처리 가능하더라구요.

private fun hideBackgroundText() {
        binding.root.post {
            binding.tvCardHomeTitle.visibility = View.GONE
            binding.tvCardHomeTitle2.visibility = View.GONE
        }
    }

post 를 사용하면 Activity 에서 해줘야했던 Runnable 과 Handler 를 알아서 해줍니다.

 

post() 를 따라 들어가봤을 때

post() 

public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }

        // Postpone the runnable until we know on which thread it needs to run.
        // Assume that the runnable will be successfully placed after attach.
        getRunQueue().post(action);
        return true;
    }

뭐 알아둡시다.

댓글