I am a newbie to Android Development and I am stuck with creating a RecyclerView in fragment.
I created 2 adapters (AdapterAll.kt for multiple fragments under Tablayout and MainAdapter.kt for a fragment that I want to create recyclerview on) but cannot invoke MainAdapter.kt. MainActivity.kt invokes AdapterAll.kt but not MainAdapter.kt. I believe this is why I can create Tablayout with fragments but cannot create a Recyclerview on a fragment.
Thank you very much!
Codes are below:
MainActivity.kt
import controller.AdapterAll
import controller.MainAdapter
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewPager.adapter = AdapterAll(supportFragmentManager)
tabLayoutId.setupWithViewPager(viewPager)
tabLayoutId.setTabTextColors(Color.GRAY, Color.parseColor("white"))
recyclerView_main.layoutManager = LinearLayoutManager(this)
recyclerView_main.adapter = MainAdapter()
}
}
AdapterAll.kt
class AdapterAll(fragmentManager: FragmentManager):
FragmentPagerAdapter(fragmentManager) {
override fun getItem(position: Int): Fragment {
when (position) {
0 -> return Function1()
1 -> return Function2()
2 -> return Function3()
3 -> return Function4()
4 -> return Function5()
5 -> return Function6()
6 -> return Function7()
}
return Function1()
}
override fun getCount(): Int {
return 7
}
override fun getPageTitle(position: Int): CharSequence? {
when (position) {
0 -> return "Function 1"
1 -> return "Function 2"
2 -> return "Function 3"
3 -> return "Function 4"
4 -> return "Function 5"
5 -> return "Function 6"
6 -> return "Function 7"
}
return null
}
}
MainAdapter.kt
class MainAdapter: RecyclerView.Adapter<CustomViewHolder>() {
override fun getItemCount(): Int {
return 10
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val cellForRow = layoutInflater.inflate(R.layout.fragment_function1, parent, false)
return CustomViewHolder(cellForRow)
}
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
holder.view.textView_video_title.text = "123"
}
}
class CustomViewHolder(val view: View): RecyclerView.ViewHolder(view) {
}
Your Adapter is ok. If I am not wrong you want a recyclerView in your Fragments, but why you create a recyclerView in you Activity. Create a recyclerView in your Fragments and set the MainAdapter.kt in the recyclerView.
class FragmentOne : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_blank, container, false)
view.recyclerView.layoutManager = LinearLayoutManager(activity)
view.recyclerView.adapter = MainAdapter()
return view
}}