我一直在网上跟踪创建RecyclerView的示例。我唯一不同的是将RecyclerView放入Fragment中,而不是将其放入MainActivity中。RecyclerView可以很好地显示数据。但是,当我导航到另一个Fragment时,应用程序崩溃,并抛出与RecyclerView相关的异常:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$ViewHolder.shouldIgnore()' on a null object reference
这是一个重现的最小示例:
主要活动:
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_layout) } }
main_layout:
RecyclerFragment:
class RecyclerFragment : Fragment() { private val data = listOf("Moscow", "Washington") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { setHasOptionsMenu(true) val view = inflater.inflate(R.layout.recycler_list, container, false) view.findViewById(R.id.list)?.apply { adapter = RecyclerAdapter(data) } return view } override fun onCreateOptionsMenu(menu: Menu?, menuInflater: MenuInflater) { menuInflater.inflate(R.menu.menu, menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { return when (item?.itemId) { R.id.navigate -> { fragmentManager?.beginTransaction()?.replace(R.id.fragment, HelloFragment())?.commit() true } else -> super.onOptionsItemSelected(item) } } }
recycler_list:
RecyclerAdapter:
class RecyclerAdapter(private val data: List): RecyclerView.Adapter () { inner class ViewHolder(val view: CardView): RecyclerView.ViewHolder(view) override fun onCreateViewHolder(root: ViewGroup, viewType: Int): ViewHolder { val listItem = LayoutInflater.from(root.context) .inflate(R.layout.list_item, root, false) as CardView return ViewHolder(listItem) } override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { viewHolder.view.findViewById (R.id.text).text = data[position] } override fun getItemCount() = data.size }
项目清单:
菜单:
HelloFragment:
class HelloFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.hello, container, false) } }
你好:
此实现有问题吗?如何在片段中使用RecyclerView?