Kotlin: onPrepareOptionsMenu() doesn't execute in Fragment - java

In my Fragment class, I have placed:
setHasOptionsMenu(true)
requireActivity().invalidateOptionsMenu()
and I am overriding the onPrepareOptionsMenu() like this
override fun onPrepareOptionsMenu(menu: Menu) {
val item : MenuItem = menu.findItem(R.id.home_popup_archive)
requireActivity().invalidateOptionsMenu()
if(item.title == "Archive"){
item.title == "Unarchive"
}
return super.onPrepareOptionsMenu(menu)
}
I also tried to override onCreateOptionsMenu, but the function code doesn't execute. There's no error though.
These are the links I have looked at. None helped.
Using onPrepareOptionsMenu instead of onCreateOptionsMenu in Fragment
onPrepareOptionsMenu not getting called in Fragments
https://android.i-visionblog.com/android-changing-menu-items-at-run-time-48970f0cf1b7
Mainly followed this link:
How to change menu item text dynamically in Android
I am trying to change the text of a menu item. Would appreciate some help.
UPDATE
Posting the whole code now for help.
class ShowAllArchivedImagesFragment : Fragment() {
private lateinit var bindingUserImages: FragmentShowAllUserImagesBinding
private var adapter: OptionsForArchivedImagesAdapter? = null
private var recyclerView: RecyclerView? = null
private var userImagesList: MutableList<HomePostModel>? = null
private var getPostId: String = ""
private var getPostPosition: String = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setHasOptionsMenu(true)
// bind and inflate layout
bindingUserImages = FragmentShowAllUserImagesBinding.inflate(layoutInflater)
// get recyclerview id
recyclerView = bindingUserImages.fragShowAllUserImagesRecyclerView
// get layout manager
val linearLayoutManager = LinearLayoutManager(context)
// speed ups
recyclerView!!.setHasFixedSize(true)
recyclerView!!.setItemViewCacheSize(20)
recyclerView!!.layoutManager = linearLayoutManager
// set adapter
userImagesList = ArrayList()
adapter =
context?.let { OptionsForArchivedImagesAdapter(it, userImagesList as ArrayList<HomePostModel>) }
recyclerView!!.adapter = adapter
// get postid, postPosition from ShowUploadedImagesOnProfileAdapter
val preference = context?.getSharedPreferences("PREFS", Context.MODE_PRIVATE)
if (preference != null) {
getPostId = preference.getString("postId", "none").toString()
getPostPosition = preference.getString("postPosition", "none").toString()
}
DisplayUserArchivedImages()
bindingUserImages.fragmentShowAllUserImagesCloseBtn.setOnClickListener {
requireActivity().onBackPressed()
}
// requireActivity().invalidateOptionsMenu()
// Inflate the layout for this fragment
return bindingUserImages.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.home_fragment_pop_up_menu_item,menu)
val item: MenuItem = menu.findItem(R.id.home_popup_archive)
if(item.title == "Archive")
{
item.title == "Unarchive"
}
}

Here is my approach:
Added setHasOptionsMenu(true) to
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setHasOptionsMenu(true)
...
}
then
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.home_fragment_pop_up_menu_item,menu)
val item: MenuItem = menu.findItem(R.id.home_popup_archive)
if(item.title == "Archive") {
item.title = "Unarchive"
}
}
and it is working perfectly!!

Related

Sending data from Fraggment_A in Activity 1 to Fragment_B in Activity 2

I have a Fragment_A on Activity_1 and whenever a Button is clicked in the Fragment_A I have to start Activity_2 witch have a Fragment_B
So i need to send a user_Id from the Fragment_A in Activity 1 to the Fragment_B in activity_2.
Is there any way to send the data directly from Frament_A in Activity_1 to Fragment_B in Activity_2?
I am a student , so i am a beginner and i did found this question here but i didn't understand what to do to solve this
I did find some solution about interface but i didn't know how to do it
i keep getting class_id null
Language : Kotlin
Class : ClassesAdapter
class ClassesAdapter(val c:Fragment,val l:android.content.Context? ,val classeslist: ArrayList<Classes>) : RecyclerView.Adapter <ClassesAdapter.ClassesViewHolder> (){
lateinit var auth: FirebaseAuth
lateinit var DataBase : DatabaseReference
lateinit var DataBase2 : DatabaseReference
lateinit var clipboardManager: ClipboardManager
private lateinit var mListener :onItemClickListener
interface onItemClickListener {
fun onItemClick(position :Int)
}
/*fun setOnItemClickListener(listener : onItemClickListener){
// mListener=listener
}*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClassesViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.class_items2,parent,false)
//return ClassesViewHolder(itemView,mListener)
return ClassesViewHolder(itemView,)
}
override fun onBindViewHolder(holder: ClassesViewHolder, position: Int) {
val currentitem = classeslist[position]
holder.classname.text = currentitem.name
holder.classrole.text = currentitem.role
holder.itemView.setOnClickListener {
val intent = Intent(l, DetailedClassActivity::class.java)
intent.putExtra("classId", currentitem.class_id)
l!!.startActivity(intent)
}
Class : Acttivity2 who has the fragment iwant to send it the class_id`
package com.example.myclass1
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.viewpager2.widget.ViewPager2
import com.example.myclass1.databinding.ActivityDetailedClassBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.firebase.auth.FirebaseAuth
class DetailedClassActivity : DrawerBaseActivity() {
private lateinit var binding: ActivityDetailedClassBinding
//lateinit var toggle: ActionBarDrawerToggle
override lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityDetailedClassBinding.inflate(layoutInflater)
setContentView(binding.root)
// add it to change the toolbar title's to the activity name
val actionBar = supportActionBar
if (actionBar != null) {
val dynamicTitle: String = HomeActivity::class.java.simpleName
//Setting a dynamic title at runtime. Here, it displays the current activity name
actionBar.setTitle("Home")
}
// navigate between documents ,notification and chatroom : tabLayout
val tablayout2 : TabLayout =findViewById(R.id.tab_layout2)
val viewpager21 : ViewPager2 =findViewById(R.id.viewPager21)
val adapter =PagerAdapter2(supportFragmentManager,lifecycle)
viewpager21.adapter = adapter
TabLayoutMediator(tablayout2, viewpager21) { tab, position ->
when(position){
0->{tab.text="Documents"}
1->{tab.text="Note"}
2->{tab.text="ChatRoom"}
}
}.attach()
val intent=getIntent()
var classId= intent.getStringExtra("classId")
fun getMyData(): String? {
return classId
}
}
class : fragment B
enter code here
btnAddcourse.setOnClickListener {
var nameofthecourse = Coursename.text.toString().trim()
var course_id :String?=DataBase3.push().key
var classId = arguments?.getString("classId")
val dateofthecourse: String = formatTimeStamp()
if (TextUtils.isEmpty(nameofthecourse)) {
// No name added
Coursename.error = "No name added !! Please enter the name of the class"
}
else{
courseList.add(Course(course_id,nameofthecourse,dateofthecourse,classId))
coursesAdapter.notifyDataSetChanged()
Toast.makeText(activity,"Adding Course Success", Toast.LENGTH_SHORT).show()
//Toast.makeText(activity,"class_id is null ", Toast.LENGTH_SHORT).show()
if (classId != null) {
addCourseToDataBase(course_id!!,nameofthecourse,dateofthecourse,classId)
}else{
Toast.makeText(activity,"class_id is null ", Toast.LENGTH_SHORT).show()
}
}
}
fragmentA
button.setOnClickListener {
val intent = Intent(requireContext(), Activity2::class.java)
intent.putExtra("user_Id", user_Id)
startActivity(intent)
}
activity2
val intent = getIntent()
val message = intent.getStringExtra("user_Id")
val bundle = Bundle()
bundle.putString("user_Id", message) //the part i updated
val fragmet= fragment_B()
fragmet.setArguments(bundle)
fragmentB
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_B, container, false)
val bundle = this.arguments //the part i updated
val myString = bundle!!.getString("user_Id", "defaultValue") //the part i updated
}
1-Read About Singleton Design Pattern
for make user id global in all app
read it to understand
2-Shared Preference :save user id to can using for all app
Shared Preferences
3-you can try Navigation Args : better choose for performance
and can use it for movement through you app
Navigation

Can You smooth scroll to new position within RecyclerView (before it is shown) and then show insert animation?

Hello fellow programmers!
I am currently facing problem with RecyclerView's add animation with smooth scroll simulataneously.
Problem
I have implemented RecyclerView with ListAdapter and DiffUtil for cool animations (insert, remove). The problem is that I can't get it to smooth scroll to added position without cancelling insert animation.
User is supposed to type in 'exercise name' and then push 'add' button to add it to current 'exercise list'. Then this exercise should be added to RecyclerView list. Everything works fine here, but I can't achieve smooth scroll to new item position without cancelling (or accelerating) insert animation.
viewModel.exerciseListLiveData.observe(viewLifecycleOwner, {
adapter.submitList(it) {
// Cancels insert animation (or accelerates it rapidly) - bad UX...
layoutManager.smoothScrollToPosition(recyclerView, RecyclerView.State(), 0)
}
})
On the other hand, substituting smoothScrollToPosition with scrollToPosition works fine but when there's more items (recycler's view is filled from top to bottom) it blinks on scroll. I know it's rather jump than smooth scroll but then, why is it working with add animation so it doesn't cancel or accelerate?
viewModel.exerciseListLiveData.observe(viewLifecycleOwner, {
adapter.submitList(it) {
// Works fine (recyclerView is scrolling to added position)
// but when there's no room to display more items - it scrolls to it with blink...
// which I simply can't stand!
layoutManager.smoothScrollToPosition(recyclerView, RecyclerView.State(), 0)
}
})
Possible solution?
I'm supposed to first smoothScrollToPosition(0) to top-most position, then call submitList(it) and finally call scrollToPosition(0) but I can't achieve that (it is doing so fast, simultaneously, that it's layering each other). Maybe I should use coroutines? Don't know...
How am I supposed to add proper delay? Maybe I am doing something wrong because i read that some programmers had this autoscroll when added item.
Code sample
Adapter
class ExercisesListAdapter :
ListAdapter<Exercise, ExercisesListAdapter.ExerciseItemViewHolder>(ExercisesListDiffUtil()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExerciseItemViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding: ItemRecyclerviewExerciseBinding =
DataBindingUtil.inflate(inflater, R.layout.item_recyclerview_exercise, parent, false)
return ExerciseItemViewHolder(binding)
}
override fun onBindViewHolder(holder: ExerciseItemViewHolder, position: Int) {
val currentExercise = getItem(position)
holder.bind(currentExercise)
}
override fun getItemId(position: Int): Long {
return getItem(position).id
}
// Item ViewHolder class
class ExerciseItemViewHolder(private val binding: ItemRecyclerviewExerciseBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(itemExercise: Exercise) {
binding.textCardExerciseName.text = itemExercise.name
}
}
}
DiffUtil
class ExercisesListDiffUtil: DiffUtil.ItemCallback<Exercise>() {
override fun areItemsTheSame(oldItem: Exercise, newItem: Exercise): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Exercise, newItem: Exercise): Boolean {
return oldItem == newItem
}
}
ViewModel
class CreateWorkoutViewModel(private val repository: WorkoutRepository) : ViewModel() {
private var exerciseId = 0L
private var exerciseList = mutableListOf<Exercise>()
val exerciseName = MutableLiveData<String?>()
private val _exerciseListLiveData = MutableLiveData<List<Exercise>>()
val exerciseListLiveData: LiveData<List<Exercise>>
get() = _exerciseListLiveData
fun onAddExercise() {
if (canValidateExerciseName())
addExerciseToList()
}
fun onAddWorkout() {
exerciseList.removeAt(2)
_exerciseListLiveData.value = exerciseList.toList()
}
private fun canValidateExerciseName(): Boolean {
return !exerciseName.value.isNullOrBlank()
}
private fun addExerciseToList() {
exerciseList.add(0, Exercise(exerciseId++, exerciseName.value!!))
_exerciseListLiveData.value = exerciseList.toList()
}
}
Fragment
class CreateWorkoutFragment : Fragment() {
lateinit var binding: FragmentCreateWorkoutBinding
lateinit var viewModel: CreateWorkoutViewModel
lateinit var recyclerView: RecyclerView
lateinit var adapter: ExercisesListAdapter
lateinit var layoutManager: LinearLayoutManager
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =
DataBindingUtil.inflate(inflater, R.layout.fragment_create_workout, container, false)
setViewModel()
setRecyclerView()
// Observers:
// Update RecyclerView list on change
viewModel.exerciseListLiveData.observe(viewLifecycleOwner, {
adapter.submitList(it) {
layoutManager.smoothScrollToPosition(recyclerView, RecyclerView.State(), 0)
}
})
return binding.root
}
private fun setRecyclerView() {
recyclerView = binding.recyclerviewExercises
setLayoutManager()
setAdapter()
}
private fun setLayoutManager() {
layoutManager = LinearLayoutManager(context)
recyclerView.layoutManager = layoutManager
}
private fun setAdapter() {
adapter = ExercisesListAdapter()
adapter.setHasStableIds(true)
recyclerView.adapter = adapter
}
private fun setViewModel() {
val dao = WorkoutDatabase.getInstance(requireContext()).workoutDAO
val repository = WorkoutRepository(dao)
val factory = CreateWorkoutViewModelFactory(repository)
viewModel = ViewModelProvider(this, factory).get(CreateWorkoutViewModel::class.java)
binding.viewModel = viewModel
binding.lifecycleOwner = this
}
}
EDIT
I got it working but it's not 'elegant' way and insert animation is canceled through process :/
adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if(layoutManager.findFirstCompletelyVisibleItemPosition() == 0)
layoutManager.scrollToPosition(0)
else {
recyclerView.clearAnimation()
layoutManager.smoothScrollToPosition(recyclerView, RecyclerView.State(), 0)
}
}
})

How would I get the context of a RecyclerView List Item?

I am new to Firebase and RecyclerViews and I am trying to get a list of ingredients from my Firebase Database and I want to create checkboxes for every item I retrieve from the database. I got as far as creating a RecyclerView and adapter for my Firebase Query but binding lists from the query doesn't seem to be covered anywhere I could find.
Please find below the code for putting the data into the recycler view as well as the layout files being used for the recycler view.
Data being retrieved
that I want to display the original field of my object as checkboxes
ShoppingListFragment.kt
class ShoppingListFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Enable Firestore logging
FirebaseFirestore.setLoggingEnabled(true)
//Firestore
firestore = Firebase.firestore
// Get recipes that the user has liked up to ${LIMIT}
query = firestore.collection("recipes").whereArrayContains(
"plannedBy",
Firebase.auth.uid.toString()
)
.orderBy("name", Query.Direction.ASCENDING)
.limit(LIMIT.toLong())
// Init the adapter to hold the recipe objects.
adapter = object : ShoppingListAdapter(query) {
override fun onDataChanged() {
if (itemCount == 0) {
shoppingListRecycler.visibility = View.GONE
viewEmpty.visibility = View.VISIBLE
} else {
shoppingListRecycler.visibility = View.VISIBLE
viewEmpty.visibility = View.GONE
}
}
override fun onError(e: FirebaseFirestoreException) {
// Show a snackbar on errors
view?.let {
Snackbar.make(
it,
"Error: check logs for info.", Snackbar.LENGTH_LONG
).show()
}
}
}
...
}
...
}
ShoppingListAdapter.kt
open class ShoppingListAdapter(query: Query) :
FirestoreAdapter<ShoppingListViewHolder>(query) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShoppingListViewHolder {
return ShoppingListViewHolder(
ItemShoppingListBinding.inflate(
LayoutInflater.from(parent.context), parent, false))
}
override fun onBindViewHolder(holder: ShoppingListViewHolder, position: Int) {
holder.bind(getSnapshot(position))
}
}
ShoppingListViewHolder.kt
class ShoppingListViewHolder(val binding: ItemShoppingListBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(snapshot: DocumentSnapshot) {
val recipe = snapshot.toObject<Recipe>() ?: return
binding.listTitle.text = recipe.name
if(recipe.ingredients.size > 1) {
binding.shoppingListItem.text = recipe.ingredients[0].original
for(i in 1 until recipe.ingredients.size) {
val checkBox = CheckBox() //Not sure what to put here as the context for my recyclerview List Item
checkBox.text = recipe.ingredients[i].original
checkBox.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
binding.shoppingListContainer.addView(checkBox)
}
} else {
binding.shoppingListItem.text = recipe.ingredients[0].original
}
}
}
I have tried passing a context parameter through ShoppingListViewHolder.kt and in turn adding that parameter to the adapter and so forth like so.
class ShoppingListViewHolder(val binding: ItemShoppingListBinding, val context: Context) : RecyclerView.ViewHolder(binding.root) {
fun bind(snapshot: DocumentSnapshot) {
val recipe = snapshot.toObject<Recipe>() ?: return
binding.listTitle.text = recipe.name
if(recipe.ingredients.size > 1) {
binding.shoppingListItem.text = recipe.ingredients[0].original
for(i in 1 until recipe.ingredients.size) {
val checkBox = CheckBox(context)
...
}
ShoppingListFragment.kt
// Init the adapter to hold the recipe objects.
adapter = object : ShoppingListAdapter(query, requireContext()) {
override fun onDataChanged() {
if (itemCount == 0) {
shoppingListRecycler.visibility = View.GONE
viewEmpty.visibility = View.VISIBLE
} else {
shoppingListRecycler.visibility = View.VISIBLE
viewEmpty.visibility = View.GONE
}
}
override fun onError(e: FirebaseFirestoreException) {
// Show a snackbar on errors
view?.let {
Snackbar.make(
it,
"Error: check logs for info.", Snackbar.LENGTH_LONG
).show()
}
}
}
But all that did was create a huge amount of white space between entries. After some debugging, it looks like passing the context from the fragment gave it the MainActivity context. I'm not too sure where to go from here and any help would be appreciated. Thank you!
you can use binding.root.context except passing context

Android: Presist the UI State and Data in Android(Kotlin)

I have A Bottom Navigation Bar Using Navigation Components It Contain 3 Fragments let Say A(Home), B And C. When I Moved From B To C Fragment B Destroys And Similarly C To B C Destroys. When I Re-Select A It Again Makes Network Call Fetches The Data and Display. I Don't Want To Make A Network Request Again And Again When Fragment Destroys Or Re-Selected.
I'm Using ViewModel, Retrofit, LiveData, Coroutines And Kotlin.
Please Help Me To Fix This Problem
Base Fragment
abstract class BaseFragment<VM: ViewModel, VB: ViewBinding, R: BaseRepository>:Fragment() {
private var _viewBinding: VB? = null
protected val viewBinding
get() = _viewBinding!!
protected lateinit var viewModel: VM
protected lateinit var userTokenData: UserTokenData
protected lateinit var remoteDataStore: RemoteDataSource
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
remoteDataStore = RemoteDataSource()
userTokenData = UserTokenData(requireContext())
_viewBinding = getFragmentBinding(inflater, container)
val factory = ViewModelFactory(getRepository())
viewModel = ViewModelProvider(this, factory).get(getViewModelClass())
lifecycleScope.launch {
userTokenData.token.first()
}
return viewBinding.root
}
abstract fun getViewModelClass():Class<VM>
abstract fun getFragmentBinding(inflater: LayoutInflater, container: ViewGroup?): VB
abstract fun getRepository(): R
override fun onDestroyView() {
super.onDestroyView()
Log.d(MyTAG, "onDestroyView")
_viewBinding = null
}
Home Fragment
class HomeFragment : BaseFragment<HomeViewModel, FragmentHomeBinding, UserRepository>() {
override fun getViewModelClass() = HomeViewModel::class.java
override fun getFragmentBinding(
inflater: LayoutInflater,
container: ViewGroup?
) = FragmentHomeBinding.inflate(inflater, container, false)
override fun getRepository(): UserRepository {
val token = runBlocking { userTokenData.token.first() }
return UserRepository(remoteDataStore.buildApi(UserApi::class.java, token))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewBinding.progressBar.visible(true)
viewModel.user.observe(viewLifecycleOwner, Observer {
when(it){
is Resources.Success -> {
updateUI(it.value.user)
}
is Resources.Loading -> {
viewBinding.progressBar.visible(true)
}
}
})
}
fun updateUI(user: User){
viewBinding.progressBar.visible(false)
viewBinding.email.text = user.email
viewBinding.name.text = user.name
}
}
In each Fragment, put this before onCreate
private val myViewModel: MyViewModel by activityViewModels()
Also, in order to do that, you will need to have this dependency:
implementation "androidx.fragment:fragment-ktx:1.2.5"

How to open a DialogFragment written in Kotlin class from a Java class

I created a WaterQualityChecksDialogFragment, please correct if I have not written it correctly.
WaterQualityChecksDialogFragment.kt
class WaterQualityChecksDialogFragment : DialogFragment() {
#Inject
private lateinit var app: App
fun newTargetInstance(): WaterQualityChecksDialogFragment {
val fragment = WaterQualityChecksDialogFragment()
return fragment
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
app!!.bus.post(ScreenDimEvent(false))
val builder = AlertDialog.Builder(activity!!.applicationContext)
// Get the layout inflater
val inflater = activity!!.layoutInflater
#SuppressLint("InflateParams")
val inflatedView = inflater.inflate(R.layout.dialog_water_quality_cheks, null)
builder
.setView(inflatedView)
.setCancelable(false)
/*
* setPositiveButton and setNeutralButton are also set (and overridden) in {#link #onStart}
* to stop Android automatically closing the dialog on click
*/
.setPositiveButton(R.string.fuel_order_signature_dialog_save) { dialog, id ->
}
.setNeutralButton(R.string.fuel_order_signature_dialog_clear) { dialog, id ->
}
val dialog = builder.create()
// Stop touch events outside the dialog from cancelling/dismissing
dialog.setCanceledOnTouchOutside(false)
return dialog
}
interface WaterQCChecksDialogListener {
fun onDialogPositiveClick(dialog: WaterQualityChecksDialogFragment)
fun onDialogNegativeClick(dialog: WaterQualityChecksDialogFragment)
}
}
ServiceOrderDialogHelper.java
public void showWaterQCChecksDioalog(){
//Cannot call newTargetInstance() method.
waterQualityChecksDialogFragment = WaterQualityChecksDialogFragment.newTargetInstance()
}
Put newTargetInstance() inside companion object to make this static like java
companion object {
fun newTargetInstance(): WaterQualityChecksDialogFragment {
val fragment = WaterQualityChecksDialogFragment()
return fragment
}
}
And call from java like below:
WaterQualityChecksDialogFragment.Companion.newTargetInstance();
Please check this code, it may helps you
class DialogClassSample : DialogFragment() {
companion object {
fun newInstance(): DialogClassSample {
val dialog = DialogClassSample()
return dialog
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
isCancelable = false
return inflater.inflate(R.layout.view, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setListener()
}
fun setListener() {
button.setOnClickListener({
dismiss()
})
}
override fun onResume() {
super.onResume()
val window = dialog?.window
val size = Point()
val display = window?.windowManager?.defaultDisplay
display?.getSize(size)
val width = size.x
window?.setLayout((width * 0.85).toInt(), WindowManager.LayoutParams.WRAP_CONTENT)
window?.setGravity(Gravity.CENTER)
}
}
and call fron your class
val dialog = DialogClassSample.newInstance()//show dialog description according to user type
dialog.show(activity?.supportFragmentManager?.beginTransaction(), DialogClassSample::class.java.name)
In on resume we have set dialog size dynamically ,because in some bigger size dialog its look not good so you can use as per your requiremnent

Categories

Resources