kotlin在fragment中不能像activity中直接通过id调用控件了,有什么办法吗

kotlin在fragment中不能像activity中直接通过id调用控件了,有什么办法吗

问题描述:

kotlin中 在fragment中不能像activity中直接通过id调用控件了,有什么办法吗

在fragment中复写这个 onCreateView的时候实例化view,用view去findViewById,语法可以参考下边的

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater!!.inflate(R.layout.xxxx, container, false)
        val iv_card = view.findViewById(R.id.xxxx) as ImageView
        iv_card.setImageResource(xxxxxxxxx])
        return view
    }

不能直接用id的原因,你xml没有载入,会导致使用id的时候会报空指针,如果需要使用,在onCreateView return view后,在onViewCreate函数中使用Id直接调用,onViewCreate会在onCreateView后执行

@vFirelonely 的方法是正确的,但是方法名称错了,应该是onViewCreated