Similar to `by`, but for other methods than get/set methods - kotlin

I only just discovered the by keyword for class, and it seems that it only works for get/set methods. But what about other methods? For example, in the code below, if I omit override fun suggestSelection(...}, it does not seem to return fallback.suggestSelection(text, selectionStartIndex, selectionEndIndex, defaultLocales);. As you see, all it does is calling the same method in fallback with the same argument. Is this the only way or is there anything to make fallback automatically called for this?
inner class MyTextClassfier(private val fallback:TextClassifier) : TextClassifier by fallback
{
override fun suggestSelection(
text: CharSequence,
selectionStartIndex: Int,
selectionEndIndex: Int,
defaultLocales: LocaleList?
): TextSelection
{
return fallback.suggestSelection(text, selectionStartIndex, selectionEndIndex, defaultLocales);
}
Adding full code as requested below. It needs the default generated Android project structure by Android Studio.
MainActivity.kt
package com.stackoverflow.test
import android.content.Context
import android.os.Bundle
import android.os.LocaleList
import android.util.Log
import android.view.textclassifier.TextClassification
import android.view.textclassifier.TextClassificationManager
import android.view.textclassifier.TextClassifier
import android.view.textclassifier.TextSelection
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textClassificationManager = getSystemService(Context.TEXT_CLASSIFICATION_SERVICE) as TextClassificationManager;
val defaultOne = textClassificationManager.textClassifier;
val txt = findViewById<TextView>(R.id.textview1);
txt.setTextClassifier(MyTextClassfier(defaultOne));
}
inner class MyTextClassfier(private val fallback:TextClassifier) : TextClassifier by fallback
{
override fun suggestSelection(
text: CharSequence,
selectionStartIndex: Int,
selectionEndIndex: Int,
defaultLocales: LocaleList?
): TextSelection
{
return fallback.suggestSelection(text, selectionStartIndex, selectionEndIndex, defaultLocales);
//return TextSelection.Builder(0,0).build();
}
override fun classifyText(
text: CharSequence,
startIndex: Int,
endIndex: Int,
defaultLocales: LocaleList?
): TextClassification
{
//Selection ended. User has lifted his finger.
Log.d("stack", "classifyText is called.");
return TextClassification.Builder().build();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="#+id/textview1"
android:text="#string/large_text"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textIsSelectable="true"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Related

Getting error while trying to implement automatic image slider in fragments | Kotlin

I'm trying to do Automatic image slider in fragment in kotlin. Any possible solutions??
I tried couple of other things also. But not a possible solution, I can do image slide inside the main activity but not to do the automatic sliding in fragments....
fragment_home.xml
Here is the XML File
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".HomeFragment">
<!-- TODO: Update blank fragment layout -->
<com.denzcoskun.imageslider.ImageSlider
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/imageSlider"
app:iss_auto_cycle="true"
app:iss_delay="0"
app:iss_placeholder="#color/grey_font"
app:iss_error_image="#color/grey_font"
app:iss_corner_radius="5"
app:iss_selected_dot="#drawable/default_selected_dot"
app:iss_unselected_dot="#drawable/default_unselected_dot"
app:iss_period="1000">
</com.denzcoskun.imageslider.ImageSlider>
</FrameLayout>
HomeFragment.kt
//This is kotlin file
package com.example.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.denzcoskun.imageslider.ImageSlider
import com.denzcoskun.imageslider.constants.ScaleTypes
import com.denzcoskun.imageslider.models.SlideModel
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [HomeFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class HomeFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
//Here it is showing error on FindViewById
val imageSlider = findViewById<ImageSlider>(R.id.imageSlider) // HERE IS THE ERROR
val imageList = ArrayList<SlideModel>()
imageList.add(SlideModel("https://www.flickr.com/photos/zillniazi/44334678732","Babusar"))
imageList.add(SlideModel("https://www.flickr.com/photos/zillniazi/44334678732","Babusar"))
imageList.add(SlideModel("https://www.flickr.com/photos/zillniazi/44334678732","Babusar"))
imageList.add(SlideModel("https://www.flickr.com/photos/zillniazi/44334678732","Babusar"))
imageList.add(SlideModel("https://www.flickr.com/photos/zillniazi/44334678732","Babusar"))
imageSlider.setImageList(imageList, ScaleTypes.FIT)
return inflater.inflate(R.layout.fragment_home, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
#JvmStatic
fun newInstance(param1: String, param2: String) =
HomeFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}

RecyclerView doesn't appear on screen

The list doesn't display on screen and it doesn't throw any error.
Am I doing something wrong connecting the adapter and layoutmanager?
Whenever I open the fragment it writes the following line: "W/RecyclerView: No adapter attached; skipping layout" and it doesn't change anything to the fragment.
This is the MainActivity.kt:
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ListView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
val addnewmoviefragment = AddNewMovieFragment()
val movielistfragment = MovieListFragment()
val moviedetailsfragment = MovieDetailsFragment()
private var layoutManager: RecyclerView.LayoutManager? = null
private var adapter: RecyclerView.Adapter<MovieListViewAdapter.ViewHolder>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
replaceFragment(movielistfragment)
val movies: MutableList<Movies> = initList()
layoutManager = LinearLayoutManager(this)
adapter = MovieListViewAdapter(this, movies)
val button = findViewById<BottomNavigationView>(R.id.bottom_navigation)
button.setOnNavigationItemSelectedListener {
when(it.itemId){
R.id.ic_movieadd -> replaceFragment(addnewmoviefragment)
R.id.ic_moviedetails -> replaceFragment(movielistfragment)
}
true
}
//val submitButton = findViewById<Button>(R.id.submitButton)
//val cancelButton = findViewById<Button>(R.id.cancelButton)
}
private fun replaceFragment(fragment: Fragment){
if(fragment!=null){
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container, fragment)
transaction.commit()
}
}
private fun initList(): MutableList<Movies>{
return mutableListOf(
Movies(1, "Inception", "Very good movie!", "James Gun", Actors("Simeon")),
Movies(2, "Extracton", "Extracting!", "Christopher Nolan", Actors("Ivan"))
)
}
MovieListViewAdapter.kt
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.EditText
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class MovieListViewAdapter(val context: Context, val allMovies: MutableList<Movies>):
RecyclerView.Adapter<MovieListViewAdapter.ViewHolder>(){
class ViewHolder(view: View): RecyclerView.ViewHolder(view){
val id: TextView
val name: TextView
val description: TextView
val producer: TextView
val actors: TextView
init{
id = view.findViewById(R.id.movieId)
name = view.findViewById(R.id.movieNameId)
description = view.findViewById(R.id.movieDescriptionId)
producer = view.findViewById(R.id.movieProducerId)
actors = view.findViewById(R.id.movieActorsId)
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.recycler_view_row, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentMovie: Movies = allMovies[position]
holder.id.text = currentMovie.id.toString()
holder.name.text = currentMovie.name
holder.description.text = currentMovie.description
holder.producer.text = currentMovie.producer
holder.actors.text = currentMovie.actors.toString()
}
override fun getItemCount(): Int {
return allMovies.size
}
}
MovieListFragment.kt
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MovieListFragment : Fragment() {
private var layoutManager: RecyclerView.LayoutManager? = null
private var adapter: RecyclerView.Adapter<MovieListViewAdapter.ViewHolder>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view: View = inflater.inflate(R.layout.fragment_movie_list, container, false)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Toast.makeText(context, "You are viewing the movie list!", Toast.LENGTH_SHORT).show()
}
}
Movies.kt
data class Movies(
val id: Int,
val name: String,
val description: String,
val producer: String,
val actors: Actors
) {
}
Actors.kt
data class Actors(
val name: String
){}
fragment_movie_list.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MovieListFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/movieListId"
android:layout_width="389dp"
android:layout_height="589dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.246" />
</androidx.constraintlayout.widget.ConstraintLayout>
recycler_view_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/indexId"
android:layout_width="68dp"
android:layout_height="23dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.045"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.079" />
<TextView
android:id="#+id/nameId"
android:layout_width="68dp"
android:layout_height="21dp"
android:layout_marginBottom="620dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.046"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/descriptionId"
android:layout_width="68dp"
android:layout_height="19dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/nameId" />
<TextView
android:id="#+id/producerId"
android:layout_width="68dp"
android:layout_height="23dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/descriptionId" />
<TextView
android:id="#+id/actorsId"
android:layout_width="65dp"
android:layout_height="21dp"
android:layout_marginStart="16dp"
android:layout_marginTop="12dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/producerId" />
</androidx.constraintlayout.widget.ConstraintLayout>
From the code, I see that the adapter gets instantiated, but never attached to the recyclerView.
You are just missing the following line in the onViewCreated override in the fragment.
findViewById<RecyclerView>(R.id.movieListId).adapter = adapter
https://developer.android.com/guide/topics/ui/layout/recyclerview

How can I attach an adapter to my fragment?

I use Kotlin in SDK 29.
I would like to make a recyclerView in my fragment. When I run the device, it doesn't crash, the fragment appear but not the Recycler View and I have the following error :
E/RecyclerView: No adapter attached; skipping layout
Here is my code :
Adapter
Import :
import android.content.Context
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.givenaskv1.R
import kotlinx.android.synthetic.main.item_post.view.*
Code :
class PostsAdapter (val context: Context, val posts : List<Post>) :
RecyclerView.Adapter<PostsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_post, parent, false)
return ViewHolder(view)
}
override fun getItemCount() = posts.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(posts[position])
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(post: Post) {
itemView.tvUsername.text = post.user?.firstName
itemView.tvDescription.text = post.description
Glide.with(context).load(post.imageUrl).into(itemView.ivPost)
itemView.tvRelativeTime.text = DateUtils.getRelativeTimeSpanString(post.creationTimeMs)
}
}
}
Fragment
Import :
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.Navigation
import com.example.givenaskv1.R
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.android.synthetic.main.fragment_page_profil.*
Code :
class FragmentPageProfil : BottomSheetDialogFragment(), OnMapReadyCallback {
private lateinit var googleMap: GoogleMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
readFireStoreData()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_page_profil, container, false)
readFireStoreData()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btnProfilOption.setOnClickListener {
val action = FragmentPageProfilDirections.actionFragmentPageProfil2ToProfilOption()
Navigation.findNavController(it).navigate(action)
}
retourBtnprofil.setOnClickListener {
val action = FragmentPageProfilDirections.actionFragmentPageProfil2ToNotificationFragment()
Navigation.findNavController(it).navigate(action)
}
btnCalendar.setOnClickListener {
val action = FragmentPageProfilDirections.actionFragmentPageProfil2ToFragmentCalendrier()
Navigation.findNavController(it).navigate(action)
}
mapProfil.onCreate(savedInstanceState)
mapProfil.onResume()
mapProfil.getMapAsync(this)
}
override fun onMapReady(map: GoogleMap?) {
map?.let {
googleMap = it
}
}
fun readFireStoreData() {
val db = FirebaseFirestore.getInstance()
db.collection("users")
.get()
.addOnCompleteListener {
val result: StringBuffer = StringBuffer()
if(it.isSuccessful) {
for(document in it.result!!) {
result.append(document.data.getValue("firstName")).append(" ")
}
nomUtilisateur.setText(result)
}
}
}
}
Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Flux.Flux">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvPosts"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Can you please help me ?
Thank you !
You forgot to add layoutManager and orientation that's it
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvPosts"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:orientation="vertical" />
And You can also fix this function as after return the function doesn't call ever
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
readFireStoreData()
return inflater.inflate(R.layout.fragment_page_profil, container, false)
}
E/RecyclerView: No adapter attached; skipping layout error could be happened when adapter has no data.
Move readFireStoreData() function to before return inflater code
like as below.
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
readFireStoreData()
return inflater.inflate(R.layout.fragment_page_profil, container, false)
}

Does anybody know how to combine flip and swipe in a deck in Kotlin?

the user should first flip a card and see the backside and than swipe left or right. Does anybody know how to combine flip deck and swipe in Kotlin?
Flip deck looks like this: https://stuff.mit.edu/afs/sipb/project/android/docs/training/animation/cardflip.html
Swipe looks like this: https://github.com/yuyakaido/CardStackView
Thanks in advance and kind regards.
I want to create a stack for Android in Kotlin which:
Which has its Items at the same position (without offset). For example, like Tinder. One just see the first item/image of the stack.
I want to add flip and see the backside of the card. Like this: https://stuff.mit.edu/afs/sipb/project/android/docs/training/animation/cardflip.html
After the flip I want to remove the card with a swipe to the left or to the right.
So far I have a stack with the following code:
MainActivity
package com.example.stackview
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
val itemList = listOf<Int>(R.drawable.ic_launcher_background, R.drawable.ic_launcher_background, R.drawable.ic_launcher_background)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val stackAdapter = StackAdapter (this, itemList)
stack_view.adapter = stackAdapter
}
}
StackAdapter
package com.example.stackview
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
class StackAdapter(val context: Context, val list: List<Int>): BaseAdapter(){
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view = LayoutInflater.from(context).inflate(R.layout.item, parent, false)
val item = view.findViewById<ImageView>(R.id.image) as ImageView
item.setImageResource(list[position])
return view
TODO("Not yet implemented")
}
override fun getItem(position: Int): Any {
return list[position]
TODO("Not yet implemented")
}
override fun getItemId(position: Int): Long {
return position.toLong()
TODO("Not yet implemented")
}
override fun getCount(): Int {
return list.size
TODO("Not yet implemented")
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="horizontal">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<StackView
android:id="#+id/stack_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:loopViews="true"
android:animateLayoutChanges="true"/>
</FrameLayout>
</LinearLayout>

How to fix Unresolved reference: setupWithViewPager

I am trying to implement TableLayout on ViewPager but i can not use method setupWithViewPager because android studio says that it is unresolved reference.
This TableLayout and ViewPager should be implemented in fragment (AboutFragment.kt)
My ViewPager works perfectly fine without TabLayout, I mean i can swipe between fragments.
Does somebody have solution?
Here is my AboutFragment:
package hr.ferit.brunozoric.taskie.ui.fragments
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import hr.ferit.brunozoric.taskie.R
import hr.ferit.brunozoric.taskie.ui.adapters.ViewPagerAdapter
import hr.ferit.brunozoric.taskie.ui.fragments.base.BaseFragment
import kotlinx.android.synthetic.main.fragment_about.*
class AboutFragment: BaseFragment() {
override fun getLayoutResourceId(): Int {
return R.layout.fragment_about
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupPager()
}
private fun setupPager() {
viewPager.adapter = ViewPagerAdapter(fragmentManager!!)
tabLayout.setupWithViewPager(viewPager) // I have error in this line :(
}
companion object{
fun newIstance(): Fragment {
return AboutFragment()
}
}
}
Here is my ViewPagerAdapter:
package hr.ferit.brunozoric.taskie.ui.adapters
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import hr.ferit.brunozoric.taskie.ui.fragments.AboutAplicationFragment
class ViewPagerAdapter(manager :FragmentManager) : FragmentStatePagerAdapter(manager) {
companion object{
const val NUM_OF_PAGES =2
const val PAGE_ONE_TITLE = "About Application"
const val PAGE_TWO_TITLE = "About Author"
}
private val frags = mutableListOf<Fragment>(AboutAplicationFragment(),AboutAplicationFragment())
private val titles = mutableListOf(PAGE_ONE_TITLE, PAGE_TWO_TITLE)
override fun getItem(position: Int): Fragment {
return frags[position]
}
override fun getPageTitle(position :Int) : String{
return titles[position]
}
override fun getCount(): Int {
return NUM_OF_PAGES
}
}
Here is XML file with ViewPager and TabLayout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tabLayout"
/>
<TableLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
You have used <TableLayout> instead of <TabLayout>.