I'm a newbie learning kotlin and android and I'm trying out simple swipe-able views with ViewPager2.
This is my adapter code:
class ViewPagerAdapter(var images: List<Int>):
RecyclerView.Adapter<ViewPagerAdapter.ViewPagerViewHolder>()
{
inner class ViewPagerViewHolder(val binding: ItemViewPagerBinding): RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewPagerViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_view_pager,parent,false)
return ViewPagerViewHolder(bind(view))
}
override fun onBindViewHolder(holder: ViewPagerViewHolder, position: Int) {
var curImage = images[position]
holder.binding.imgview.setImageResource(curImage)
}
override fun getItemCount(): Int {
return images.size
}
}
This is my MainActivity file where I'm getting the error:
class MainActivity : AppCompatActivity() {
private lateinit var binding:ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
var image = listOf {
R.drawable.illustration
R.drawable.pexelsphoto
R.drawable.preview
R.drawable.wallpaper
R.drawable.yh
}
val adapter = ViewPagerAdapter(image)
binding.viewPager.adapter = adapter
binding.viewPager.orientation = ViewPager2.ORIENTATION_VERTICAL
}
}
This is the error I'm getting on the image variable in the ViewPagerAdapter parenthesis
Type mismatch: inferred type is List<() -> Int> but List<Int> was expected
I'm unable to find any solution online on how to fix this
CodePudding user response:
You defined the image list in wrong way, it must be like this
var image = listOf (
R.drawable.illustration,
R.drawable.pexelsphoto,
R.drawable.preview,
R.drawable.wallpaper,
R.drawable.yh
)
The expected type is List<Int>
and it is defined like above. Meanwhile you use listOf {}
which is List<() -> Int>
type.