I have this android fragment:
class MainFragment: BaseFragment(){
private val recyclerView by lazy { find<RecyclerView>(R.id.recyclerView) }
private val fab by lazy { find<FloatingActionButton>(R.id.fab) }
private val myLayoutManager by lazy { LinearLayoutManager(ctx, LinearLayoutManager.VERTICAL, false) }
private val myAdapter by lazy { MainCardAdapter(ctx, ArrayList<MainCardAdapterItem>(), R.layout.card_main_item) }
override val fragmentLayout = R.layout.fragment_main_layout
val DUMMY_TEXT = "Lorem ipsum dolor sit amet, consectetur adipiscing"
)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = super.onCreateView(inflater, container, savedInstanceState)
setHasOptionsMenu(true)
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
Log.i("TAG", "onViewCreated")
super.onViewCreated(view, savedInstanceState)
(act as MainActivity).run { showWidgetStars(true) }
recyclerView
.linkToLayoutManager(myLayoutManager)
.linkToAdapter(myAdapter)
.addItemDecorator(removedSwipeLeftDecorator)
.setOnItemChangedDuration(500)
myAdapter.run {
setAdapterItems(dummyList)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.activity_main_context, menu)
menu.findItem(R.id.action_secundary_menu).run {
isVisible = true
icon.setTintCompat(ctx, act.colorFromRes(R.color.appGreyDark))
}
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
R.id.action_secundary_menu -> {
act.showSnackBar("Clicked Secondary Menu!")
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
}
Everything works good except after i come back to this fragment (replaced in fragment manager by another, added to the backstack). When i return, i get an error saying: E/RecyclerView: No adapter attached; skipping layout
. My bet is that its something to do with lazy properties but i can't figure it why. The fragment shows good on first run, only when going back it shows no recycler view items and display this message
答案 0 :(得分:3)
因为我的属性被声明为lazy { find<View>(R.id.xxx}
,这基本上意味着它们只会从布局中膨胀一次。如果片段的视图需要再次创建,则recyclerview属性将指向旧视图。
我不确定在这种情况下如何抛出空指针异常。只需将延迟更改为var
,然后在onCreateView
上重新分配。另一件事,如果我们想要使用相同的LayoutManager
用于新的inflated recyclerview,我们必须从之前的recyclerview recyclerView.layoutManager = null
中清除它,否则会抛出一个例外layoutManager
已被绑定到另一个recyclerView。