I am trying to set a recycler view in the fragment. I have got a code that suits MainActivity. Please help me to change it for Fragment. ![enter image description here][1]
class MainActivity2 : AppCompatActivity() {
private var recyclerView: RecyclerView? = null
private var charItem: ArrayList<CharItem>? = null
private var gridLayoutManager: GridLayoutManager? = null
private var alphaAdapters: AlphaAdapters? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recycler_view_item)
gridLayoutManager =
GridLayoutManager(applicationContext, 3, LinearLayoutManager.VERTICAL, false)
recyclerView?.layoutManager = gridLayoutManager
recyclerView?.setHasFixedSize(true)
charItem = ArrayList()
charItem = setAlphas()
alphaAdapters = AlphaAdapters(applicationContext, charItem!!)
recyclerView?.adapter = alphaAdapters
}
private fun setAlphas(): ArrayList<CharItem> {
var arrayList: ArrayList<CharItem> = ArrayList()
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
}
CodePudding user response:
Class MainFragment2: 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? {
return inflater.inflate(
R.layout.fragment_category, container, false
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViews()
}
private fun initViews() {
recyclerView = findViewById(R.id.recycler_view_item)
gridLayoutManager =
GridLayoutManager(applicationContext, 3, LinearLayoutManager.VERTICAL, false)
recyclerView?.layoutManager = gridLayoutManager
recyclerView?.setHasFixedSize(true)
charItem = ArrayList()
charItem = setAlphas()
alphaAdapters = AlphaAdapters(applicationContext, charItem!!)
recyclerView?.adapter = alphaAdapters
}
private fun setAlphas(): ArrayList<CharItem> {
var arrayList: ArrayList<CharItem> = ArrayList()
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
}
}