使用kotlin的代码, 首先,这是我的错误代码。
这是我使用的扩展BaseFragment
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val cacheView = mView == null
if (cacheView) {
mView = inflater.inflate(getFragLayoutResID(), container, false)
initView(mView!!)
}
return mView
}
//When used in an activity
fun addFragment(context: FragmentActivity, fragmentContainer: Int) {
val fragmentManager = context.supportFragmentManager
val ft = fragmentManager.beginTransaction()
ft.replace(fragmentContainer, this, javaClass.simpleName).addToBackStack(javaClass.simpleName)
.commitAllowingStateLoss()
ft.setMaxLifecycle(this, Lifecycle.State.RESUMED)
}
这是我的HomeActivity
homeVideoFragment.addFragment(mContext as FragmentActivity, mainFrameLayout.id)
这是我的HomeFragment
//HomeFragment
override fun initView(view: View) {//this is my homeFragment
initAdapter()
//init()
}
private var homeVideoAdapter: HomeVideoAdapter? = null
private fun initAdapter() {//this is my init adapter
val homeVideoManager = LinearLayoutManager(mContext, RecyclerView.VERTICAL, false)
homeVideoAdapter = HomeVideoAdapter(mContext!!)
home_video_rv.layoutManager = homeVideoManager
home_video_rv.adapter = homeVideoAdapter
}
private fun init() = runBlocking {
GlobalScope.launch(Dispatchers.Main) {
initAdapter()
//GlobalScope.async(Dispatchers.IO) {
//presenter!!.getVideoClassPost(AllPort.POST_GET_VIDEO_HOME)//network requests
//}.await()
}
}
这样运行代码时,将报告错误:home_video_rv不能为空。
但是当我使用init()时,它工作正常。
虽然成功,但无法发出网络请求。
为什么会出现此问题?
答案 0 :(得分:1)
使用onViewCreated方法
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val cacheView = mView == null
if (cacheView) {
mView = inflater.inflate(getFragLayoutResID(), container, false)
}
return mView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView(view)
}