i have a fragment with a BottomNavigationView, a Spinner and a FrameLayout, in the FrameLayout appears a a new fragment with the BottomNavigationView.setOnNavigationItemSelectedListener, this is my code:
Fragment ValcuotaEvolFragment
class ValcuotaEvolFragment: Fragment() {
lateinit var fragment : Fragment
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?, savedInstanceState: Bundle?): View? {
val root = inflater.inflate(R.layout.fragment_valcuota_evol, container, false)
val menuBottom: BottomNavigationView = root.findViewById(R.id.nav_view_valcuota_evol)
val spn : Spinner = root.findViewById(R.id.spnAFP)
val db = DataBaseHandler(activity!!.applicationContext)
val afpListName : ArrayList<String> = db.getAFPNames()
fragment= ValcuotaChartFragment()
val bundle = Bundle()
spn.adapter= ArrayAdapter<String>(activity!!.applicationContext,android.R.layout.simple_spinner_dropdown_item,afpListName)
spn.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
bundle.putString("afp",spn.selectedItem.toString())
}
override fun onNothingSelected(parent: AdapterView<*>) { }
}
menuBottom.setOnNavigationItemSelectedListener {
menuItem ->
when(menuItem.itemId){
R.id.nav_evolcuota_chart -> {
fragment = ValcuotaChartFragment()
}
R.id.nav_evolcuota_data -> {
fragment = ValcuotaDataFragment()
}
}
fragment.setArguments(bundle);
val transaction = childFragmentManager.beginTransaction()
transaction.replace(R.id.frame_valcuota_evol, fragment)
transaction.addToBackStack(null)
transaction.commit()
true
}
fragment.setArguments(bundle);
val transaction = childFragmentManager.beginTransaction()
transaction.replace(R.id.frame_valcuota_evol, fragment)
transaction.addToBackStack(null)
transaction.commit()
return root
}
}
I pass to the new fragment the value "afp" through a Bundle, now i need the new fragment to do something different depending on what I select in the spinner of ValcuotaEvolFragment
this is what i need:
class ValcuotaDataFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val root = inflater.inflate(R.layout.fragment_valcuota_data, container, false)
val afp = arguments!!.getString("afp")
if(afp == "something"){
doSomething()
else {
doSomethingElse
}
return root
}
}
this actually works, but only when i change the item in the BottomNavigationView i need this works when change the item in the Spinner, thx
EDIT
The EventBus solution works fine , but now i have a new problem in ValcuotaDataFragment i have a RecyclerView, so now i need fill the RecyclerView after change the item in the Spinner, this is how i do it now:
val rcViewValcuota = root. findViewById(R.id.rc_valcuota_data) as RecyclerView
var valcuota : MutableList<ValcuotaModel>
val db = DataBaseHandler(activity!!.applicationContext)
valcuota = db.getCompleteValCuota(spinnerData.selectedItem,"desc")
rcViewValcuota.adapter= ContentValcuotaMonthlyAdapter(valcuota)
i can't access the "root" from the function listenItemChange
Okay, so when you're selecting a different item from the spinner, your fragment is not aware of it unless you pass data to fragment. So for informing the fragment, you can implement the interface if you'd like. Or my favorite you can use EventBus library to pass the data.
I'll show you how you can implement EventBus.
First, add EventBus Dependency is the Gradle file:
implementation 'org.greenrobot:eventbus:3.1.1'
Okay now create a data class for passing data say SpinnerData:
data class SpinnerData(val selectedItem:String)
Then inside your itemSelected listener, pass the data using EventBus:
spn.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
// bundle.putString("afp",spn.selectedItem.toString())
//insted add following line
EventBus.getDefault().post(SpinnerData(spn.selectedItem.toString()))
}
override fun onNothingSelected(parent: AdapterView<*>) { }
}
Then inside your ValcuotaDataFragment add the following:
#Subscribe
fun listenItemChange(spinnerData: SpinnerData){
if (spinnerData.selectedItem == "something") {
doSomething()
} else {
doSomethingElse()
}
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onStop() {
EventBus.getDefault().unregister(this)
super.onStop()
}
Now, whenever you change the spinner item Evenbus will be triggered and pass the data to the Subscribed method inside your fragment.
Hope this helps, let me know if you get stuck somewhere.
Edit:
This won't work if your fragment isn't initialized already.
SO keep your line inside your itemSelected listener for first time use:
bundle.putString("afp",spn.selectedItem.toString())
Related
I use view-pager2 and When I remove the first item of view-pager, It does not delete and still remains but another item removed.
For example, here I want to remove the first item of view pager but it's not be removed:
My Main Activity:
class MainActivity : AppCompatActivity() {
private lateinit var myPagerAdapter: MyPagerAdapter
private val mFragmentList: ArrayList<FragmentOne> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (mFragmentList.isEmpty()) {
mFragmentList.add(FragmentOne.newInstance(1))
mFragmentList.add(FragmentOne.newInstance(2))
mFragmentList.add(FragmentOne.newInstance(3))
}
myPagerAdapter = MyPagerAdapter(supportFragmentManager, lifecycle)
view_pager.adapter = myPagerAdapter
btn_show.setOnClickListener {
val dialog = Dialog(this)
dialog.setContentView(R.layout.fragment_dialog)
dialog.btn_remove.setOnClickListener {
//go to next item
view_pager.currentItem = 1
//remove first item
mFragmentList.removeAt(0)
//reload adapter
myPagerAdapter.notifyDataSetChanged()
}
dialog.show()
}
}
private inner class MyPagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount(): Int {
return mFragmentList.size
}
override fun createFragment(position: Int): Fragment {
return mFragmentList[position]
}
}
}
FragmentOne:
class FragmentOne : Fragment() {
companion object {
fun newInstance(position: Int): FragmentOne {
val fragment = FragmentOne()
val bundle = Bundle()
bundle.putInt("id", position)
fragment.arguments = bundle
return fragment
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_one, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val id = arguments?.getInt("id")
tv?.text = id.toString()
}
}
If I don't use view-pager2, Just enough to add PagerAdapter.POSITION_NONE like this answer.
Can you help me?!
If you read the documentation it says
Note: The DiffUtil utility class relies on identifying items by ID. If you are using ViewPager2 to page through a mutable collection, you must also override getItemId() and containsItem().
Taken from this post - Migrate to ViewPager2
Since you are using a mutable ArrayList() you should also override the getItemId() method in your adapter, for the itemId you need a unique ID for every fragment, I solved it using the hashCode() function like this
override fun getItemId(position: Int): Long {
return mFragmentList[position].hashCode().toLong()
}
This should remove the first fragment and get the correct fragment from the list using the itemId
Hope this solves your problem.
Actually delete functionality is working properly 0th index fragment is deleted but after calling notfiydataset changed the first fragment gets th value as 1 and second as 2.
I did the same for java, with viewpager2 and its works!
#Override
public long getItemId(int position) {
Long longtype = Long.valueOf(mFragmentList.get(position).hashCode());
return longtype;
}
#Override
public boolean containsItem(long itemId) {
return super.containsItem(itemId);
}
Suppose I have got a seek bar in the activity to change the textview font size of the fragment. What method should I pass?
I have an activity. This includes a view pager. The view pager has a pager adapter. For each item in the pager adapter, we create new instance of fragment. When I drag the SeekBar, I want to pass the value onto the fragment. I have applied interface callback and also passing argument bundle. But, when it comes to implementation and testing, the font size des not change.
Would you please advise me the way to pass one value from a seek bar of an activity to a fragment within the pager adapter ?
Here is my working :
class ChapterActivity : AppCompatActivity() , ViewPager.OnPageChangeListener {
...
val listener = object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
val scaledSize = progress * 0.6 + minimumValue
println("scaledSize : $scaledSize" )
println("scaledSize : ${scaledSize.toFloat()}" )
//txt_chapter_content.setTextSize(TypedValue.COMPLEX_UNIT_DIP, scaledSize .toFloat() );
val prefs = getPreferences(Context.MODE_PRIVATE)
val ed = prefs.edit()
ed.putFloat("fontsize", scaledSize.toFloat())
ed.apply()
val myBundle = Bundle()
myBundle.putFloat("fontsize" , scaledSize.toFloat() )
mAboutDataListener!!.onDataReceived(scaledSize.toFloat())
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
}
chapterPagerAdapter = ChapterPagerAdapter(supportFragmentManager, chapters)
// Set the Adapter and the TabLayout forward the ViewPager
chapterViewPager.adapter = chapterPagerAdapter
chapterViewPager.addOnPageChangeListener(this);
Fragment:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout forward this fragment
val view = inflater.inflate(com.books.learn.ddy.blinkist.R.layout.content_chapter, container, false)
val titleTextView = view.findViewById<TextView>(R.id.txt_chapter_title)
val contextTextView = view.findViewById<TextView>(R.id.txt_chapter_content)
contextTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, floatSize )
override fun onDataReceived(fontSize: Float) {
contextTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize );
}
If your PagerAdapter is not FragmentStatePagerAdapter,you can obtain your Fragment(e.g. FragmentOne) and update the scaled size as follows:
val page = getSupportFragmentManager().findFragmentByTag("android:switcher:${R.id.pager}:${pagerPosition}"
if (page != null) {
((FragmentOne)page).onDataReceived(scaledSize.toFloat())
}
If not feasible,check here to know how to get the Fragment instance in the viewpager,then just call it's method in activity.
I have posted an answer to a similar question here https://stackoverflow.com/a/60427448/2102794.
Fragment
class SampleFragment : Fragment(), BaseFragmentInteraction {
override fun updateSeekBarProgress(progress: Int) {
Toast.makeText(activity!!, data, Toast.LENGTH_SHORT).show()
}
}
Interface
interface BaseFragmentInteraction {
fun updateSeekBarProgress(progress: Int)
}
SeekBar Callback:
val listener = object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
val fragmentItem = (view_pager.adapter as FragmentPagerAdapter).getItem(view_pager.currentItem)
(fragmentItem as BaseFragmentInteraction).updateSeekBarProgress(progress)
}
}
You should implement a callback interface in the fragment while keeping a reference of this callback in your activity. This way when you call a function [suppose changeFontSize()] from your activity, your fragment's implementation of this method will be called. Check this answer
Keep in mind that when using ViewPager you will also have to check for current fragment visibility. Check this answer
Hope this helps.
trying to get RecyclerView from this layout :
<?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"
tools:context=".listFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclee">
</android.support.v7.widget.RecyclerView>
into main activity class :
private var mBlogList = findViewById<RecyclerView>(R.id.recyclee)
getting error :
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
any help please :)
edit 1
i use kotlin extension now
import kotlinx.android.synthetic.main.fragment_list.*
class MainActivity : AppCompatActivity() {
private lateinit var mBlogList : RecyclerView
in onCreate method :
mBlogList = recyclee
but the same error still exist
edit 2
listFragment code :
class listFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclee != null
}
companion object {
fun newInstance(): listFragment = listFragment()
}
}
edit 3
whole MainActivity code:
//this app supposed to read from FirebaseDatabase
//into Recycler view
//the RecyclerView is into Fragment layout
//i use Fragments into FrameLayout in the activity_main.xml
// the RecyclerView should be shown when navigatoinBar is clicked
//or on start of MainActivity
class MainActivity : AppCompatActivity() {
private var mDatabase:DatabaseReference? = null
private lateinit var mBlogList : RecyclerView
private var query:Query?=null
private var options:FirebaseRecyclerOptions<Blog>?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//start listFragment , RecyclerView is there
val mFragment = listFragment.newInstance()
//openFragment method is below
openFragment(mFragment)
//navigation bottom onclicklistener
navBar.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
//get data from database
mDatabase=FirebaseDatabase.getInstance().getReference().child("mall")
mDatabase?.keepSynced(true)
//here i should have recyclee but it is null i don't know why
mBlogList = recyclee
mBlogList.setHasFixedSize(true)
mBlogList.layoutManager = LinearLayoutManager(this)
//query of database
query = mDatabase?.orderByKey()
}
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
//there are 4 icons in the navigation_bottom_bar
//now we are talking about listNav icon only because it is realted
// with listFragment
when (item.itemId) {
R.id.listNav -> {
val mFragment = listFragment.newInstance()
openFragment(mFragment)
return#OnNavigationItemSelectedListener true
}
R.id.cartNav -> {
val mFragment = cartFragment.newInstance()
openFragment(mFragment)
return#OnNavigationItemSelectedListener true
}
R.id.supportNav -> {
val mFragment = supportFragment.newInstance()
openFragment(mFragment)
return#OnNavigationItemSelectedListener true
}
R.id.accountNav -> {
val mFragment = accountFragment.newInstance()
openFragment(mFragment)
return#OnNavigationItemSelectedListener true
}
}
false
}
private fun openFragment(fragment: Fragment) {
//open Fragment into FrameLayout in the main_activity.xml
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.mainFrame, fragment)
transaction.addToBackStack(null)
transaction.commit()
}
override fun onStart() {
super.onStart()
//set options for FirebaseRecyclerAdapter
options = FirebaseRecyclerOptions.Builder<Blog>()
.setQuery(query!!, Blog::class.java)
.build()
//set custom adapter
val mAdapter = object : FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
options!!) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BlogViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.cardview, parent, false)
return BlogViewHolder(view)}
override fun onBindViewHolder(holder: BlogViewHolder, position: Int, model: Blog) {
holder.setTitle(model.title)
holder.setDes(model.des)
holder.setImage(applicationContext, model.image)
}
}
mBlogList.adapter = mAdapter
}
inner class BlogViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var mView:View= itemView
//set title, des amd image with data we got from database
fun setTitle(title:String){
var postTitle = mView.findViewById<TextView>(R.id.post_title)
postTitle?.text = title
}
fun setDes(des:String){
var postDes = mView.findViewById<TextView>(R.id.post_des)
postDes?.text = des
}
fun setImage(image:String){
var postImage = mView.findViewById<ImageView>(R.id.post_title)
Picasso.get().load(image).into(postImage)
}
}
}
If you apply kotlin-android-extensions plugin then you don't need to use findViewById anymore because you can access views in the layout as if they're properties (by name). So, your onCreate could look as follows:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
assert recyclee != null
}
Edit
Since you're trying to do this in Fragment and your layout file is called
fragment_List.xml then in your Fragment you must inflate the layout first and then you can access your RecyclerView as in the example above for Activity:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_List, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
assert recyclee != null
}
If you try to access your RecyclerView in Activity before fragment_List is inflated in the Fragment then it will obviously be null (it hasn't been created yet). That's actually what you're trying to do in onCreate - it's too early as the Fragment's layout hasn't been built yet.
Edit 2
As it's seen from your code, mBlogList = recyclee is set in onCreate. Even though it's done after the ListFragment is created, it's still too early as its onCreateView hasn't been called yet and so no layout is in place.
A quick fix would be to do it in onStart as at that point ListFragment is definitely there. However, a better approach is to do the logic inside ListFragment itself and communicate with MainActivity via callbacks as described here
Try to use the findViewById on onCreate or onCreateView (if you are in a Fragment). It is happening because before this methods your layout wasn't inflated yet so Android cannot find your RecyclerView
class MainActivity : AppCompatActivity() {
private lateinit var mBlogList : RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mBlogList = findViewById<RecyclerView>(R.id.recyclee)
}
}
I would recommend you to read this: https://kotlinlang.org/docs/tutorials/android-plugin.html
Kotlin has a better way to get the reference os your views, you don't need to use findViewById =)
You cannot call findViewById from the global scope. But, you can declare it as:
private val mBlogList by lazy { findViewById<RecyclerView>(R.id.recyclee) }
...then use the variable the usual.
In this way you could access RecyclerView attributes once adapter has been loaded at onCreate() function
var recyclerView : RecyclerViewAdapterYourClass = adapter as RecyclerViewAdapterYourClass
recyclerView.yourRecyclerAttribute
I am using fragments inside my main activity and I want to send an object of my custom class "TaskWithUserAndProfile" to the TaskDetailsFragment
I found out that you can do it with Bundle and made it send a string, but things got complicated when I tried to send with Parcebale.
here are some parts of my code for better understanding:
TaskWithUserAndProfile.kt
class TaskWithUserAndProfile() : Parcelable{
override fun writeToParcel(p0: Parcel?, p1: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
var profile = Profile()
var task = Task()
var user = User()
constructor(parcel: Parcel) : this() {
//profile = parcel.read
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<TaskWithUserAndProfile> {
override fun createFromParcel(parcel: Parcel): TaskWithUserAndProfile {
return TaskWithUserAndProfile(parcel)
}
override fun newArray(size: Int): Array<TaskWithUserAndProfile?> {
return arrayOfNulls(size)
}
}
}
HomeFragment.kt
//Inside onCreateView
adapter = TasksAdapter(tasksArray) { item ->
println(item.profile)
val bundle = Bundle()
bundle.putParcelable("MyItem", item)
val taskDetailsFragment = TaskDetailsFragment()
taskDetailsFragment.arguments = bundle
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.container, taskDetailsFragment)
fragmentTransaction.addToBackStack(null)
fragmentTransaction.commit()
}
How should my class that implements the Parcebale look like and how can I then send and receive the item object in fragments?
You don't need to use Parcelable even, just simply define an TaskWithUserAndProfile variable in your TaskDetailsFragment and set in in HomeFragment.
TaskDetailsFragment.kt
class TaskDetailsFragment : Fragment() {
var selectedTask: TaskWithUserAndProfile? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
}
}
HomeFragment.kt
//Inside onCreateView
adapter = TasksAdapter(tasksArray) { item ->
val taskDetailsFragment = TaskDetailsFragment()
taskDetailsFragment.selectedTask = item
val fragmentTransaction =
fragmentManager?.beginTransaction()
fragmentTransaction?.replace(R.id.container, taskDetailsFragment)
fragmentTransaction?.addToBackStack(null)
fragmentTransaction?.commit()
}
if you wanna keep using parcelize, just try this sample:
#Parcelize
data class TaskWithUserAndProfile(var profile:Profile, var task :Task, var user:User) : Parcelable{}
I could miss something from your class but the idea should looks like this, so use annotation #Parcelize and Parcelable implementation (do not need to override any method).
Update
Thanks for reminder. You will have to add this to your gradle file:
androidExtensions {
experimental = true
}
Use this plugin:
android-parcelable-intellij-plugin-kotlin
for TaskWithUserAndProfile, Profile, Task, User models.
I want to create a dialog which contain's ViewPager inside it which have 3 pages and all pages have different layout structure. I want a solution by that i can set the layout content programmatically . I think this can be done by making fragments for each page but i don't know how to do this.
I go through these answers but i am not getting idea how to use them in my case.
Viewpager in Dialog?
ViewPager in Custom Dialog
ViewPager in simple Dialog
You can try and build your custom dialog through DialogFragment. Consider the XML layout would contain a ViewPager and the code to go about would be:
class PagerDialog : DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.element_fragment_pager_dialog, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupPager()
}
private fun setupPager() {
val pagerFragment1 = PagerFragment1.newInstance()
val pagerFragment2 = PagerFragment2.newInstance()
val pagerFragment3 = PagerFragment3.newInstance()
viewPager?.adapter = MyFragmentPagerAdapter(childFragmentManager).apply {
adapterReference = object : PageAdapterInterface {
override var fragmentList: List<Fragment> =
mutableListOf(pagerFragment1, pagerFragment2, pagerFragment3)
}
}
}
companion object {
const val tag = "PagerDialog"
}
}
I have used reference to the list because it might cause leaks when not handled correctly. So the PagerAdapterInterface would look like:
interface PageAdapterInterface {
var fragmentList: List<Fragment>
fun getItemCount() = fragmentList.size
#Throws(StackOverflowError::class)
fun getItemAt(index: Int) : Fragment {
if (index >= fragmentList.size) throw StackOverflowError()
return fragmentList[index]
}
}
Your view pager adapter can make use of this reference in manner that is accessing referentially like:
class MyFragmentPagerAdapter(childFragmentManager: FragmentManager) : FragmentStatePagerAdapter(childFragmentManager){
lateinit var adapterReference: PageAdapterInterface
override fun getItem(p0: Int): Fragment = adapterReference.getItemAt(p0)
override fun getCount(): Int = adapterReference.getItemCount()
}
Finally in your Activity or Fragment on create() or onViewCreated() functions respectively, you can initialize the dialog as shown:
class MyActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// use childFragmentManager if the code is
// used within the Fragment
val prev = supportFragmentManager.findFragmentByTag(PagerDialog.tag)
if (prev != null) {
supportFragmentManager.beginTransaction()
.remove(prev)
.addToBackStack(null)
.commit()
}
PagerDialog().show(supportFragmentManager, PagerDialog.tag)
}
}
Note: DialogFragment is deprecated on > API 28 check out https://developer.android.com/reference/android/app/DialogFragment