Reputation: 25
I have been trying to implement a viewpager2 in kotlin but i cannot figure out why am i getting an error saying no adapter attached to recycle view here is my MainActivity.kt:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
binding = ActivityMainBinding.inflate(layoutInflater)
binding.viewpager2.adapter = Viewpager2Adapter(this)
TabLayoutMediator(binding.tabLayout , binding.viewpager2){
tab, position ->
tab.text = "OBJECT ${(position + 1)}"
}.attach()
}
}
Below is viewpager2Adapter.kt ::
class Viewpager2Adapter(fa : FragmentActivity): FragmentStateAdapter(fa) {
override fun getItemCount(): Int = 3
override fun createFragment(position: Int): Fragment= Fragment2()
}
This is my fragment2.kt::
class Fragment2 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_2, container, false)
}
}
Can someone please help me by figuring out what is it that I am doing wrong. Thank you in advance :)
Upvotes: 1
Views: 1308
Reputation: 286
I think you did not use view binding properly in your MainActivity. In setContentView you should have binding.root instead of R.layout.activity_main
Here is the code for onCreate function in MainActivity:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
viewpager2Adapter = Viewpager2Adapter(this)
viewPager2 = binding.viewpager2
tabLayout = binding.tabLayout
viewPager2.adapter = viewpager2Adapter
TabLayoutMediator(tabLayout, viewPager2){
tab, position ->
tab.text = "OBJECT ${(position + 1)}"
}.attach()
}
Upvotes: 2
Reputation: 1463
The issue is that you are mixing 2 approaches of inflating activity's view, so the view is then not properly inflated. To fix your issue, replace:
setContentView(R.layout.activity_main)
binding = ActivityMainBinding.inflate(layoutInflater)
with
binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
And your code should work. The above is the regular approach to apply when you implement databindings. If you would not use databinding, the code would look like follow:
setContentView(R.layout.activity_main)
val viewpager2 = findViewById<ViewPager2>(R.id. viewpager2)
val tabLayout = findViewById<TabLayout>(R.id.tabLayout)
viewpager2.adapter = Viewpager2Adapter(this)
TabLayoutMediator(tabLayout , viewpager2){
tab, position ->
tab.text = "OBJECT ${(position + 1)}"
}.attach()
Your app would work with the above code even if you keep the databinding, but of course, using databinding and accessing views through the binding
instance is much more comfortable compared to findViewById
.
Upvotes: 0