Search code examples
kotlinbutterknife

Layout view is not initialized with Butterknife


In the following code:

class LobbyFragment : Fragment() {

    @Inject
    lateinit var lobbyFragmentHelloService: LobbyFragmentHelloService

    @BindView(R.id.lobby_fragment_hello)
    lateinit var lobbyFragmentHelloTextView: TextView

    lateinit var unbinder: Unbinder

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.lobby_fragment, container, false)
        unbinder = ButterKnife.bind(this, view)
        return view
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        sayFragmentHello()
    }

    override fun onAttach(context: Context?) {
        AndroidInjection.inject(this)
        super.onAttach(context)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        unbinder.unbind()
    }

    private fun sayFragmentHello() {
        lobbyFragmentHelloTextView.text = lobbyFragmentHelloService.sayHello()
    }
}

lobbyFragmentHelloTextView is never initialized. Butterknife is used to initialize this variable. Why is not initialized by the time sayFramentHello is called?


Solution

  • I'm not really sure what went wrong but to fix the issue, you can consider using kotlin built in synthetic binding and just get rid of butterknife. It's more efficient.

    explained here