如何将MainActivity中的RecyclerView代码改写为Fragment版本?
适配Fragment的RecyclerView实现代码
以下是将原Activity代码改写为Fragment版本的完整实现:
class AlphaFragment : Fragment() { private var recyclerView: RecyclerView? = null private var charItem: ArrayList<CharItem>? = null private var gridLayoutManager: GridLayoutManager? = null private var alphaAdapters: AlphaAdapters? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // 加载Fragment对应的布局文件 return inflater.inflate(R.layout.fragment_alpha, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 通过当前Fragment的根View获取RecyclerView实例 recyclerView = view.findViewById(R.id.recycler_view_item) gridLayoutManager = GridLayoutManager(requireContext(), 3, LinearLayoutManager.VERTICAL, false) recyclerView?.layoutManager = gridLayoutManager recyclerView?.setHasFixedSize(true) charItem = setAlphas() alphaAdapters = AlphaAdapters(requireContext(), charItem!!) recyclerView?.adapter = alphaAdapters } private fun setAlphas(): ArrayList<CharItem> { val arrayList = ArrayList<CharItem>() arrayList.add(CharItem(R.mipmap.entertainment_pic_foreground, "A Latter")) arrayList.add(CharItem(R.mipmap.general_pic_foreground, "B Latter")) arrayList.add(CharItem(R.mipmap.health_pic_foreground, "C Latter")) arrayList.add(CharItem(R.mipmap.science_pic_foreground, "D Latter")) arrayList.add(CharItem(R.mipmap.technology_pic_foreground, "E Latter")) return arrayList } }
关键修改说明
- 继承类从
AppCompatActivity改为Fragment,遵循Fragment的生命周期规范 - 用
onCreateView方法加载Fragment布局,替代Activity的setContentView - 在
onViewCreated中完成视图初始化,通过传入的根View调用findViewById获取组件 - 上下文使用
requireContext()替代applicationContext,保证上下文的有效性(仅在Fragment依附于Activity时可用) - 移除冗余的集合初始化代码,直接通过
setAlphas()赋值
注意:需确保Fragment对应的布局文件(示例中为fragment_alpha.xml)包含id为recycler_view_item的RecyclerView组件,布局结构可复用原Activity的RecyclerView配置。
内容的提问来源于stack exchange,提问作者Fary
相关产品推荐
相关产品推荐

