Alert Android opens several times and does not close with dismiss - java

I have 2 alerts in sequence, where the last one does not close with dismiss, could you help me please? Below my code snippet. I have a custom view
fun MaterialDialog.Builder.alertChangedIcon (action: () -> Unit) {
this.apply {
customView(R.layout.change_icon_dialog, false)
canceledOnTouchOutside(false)
build().run {
val btnPosition = this.findViewById(R.id.yesBtnView) as Button
btnPosition.setOnClickListener {
this.dismiss()
action.invoke()
}
}
show()
}
}
fun MaterialDialog.Builder.alertIconInfoChanged(action: () -> Unit) {
this.apply {
customView(R.layout.title_subtitle_two_buttons_dialog_prime,false)
canceledOnTouchOutside(false)
build().run {
val title = this.findViewById(R.id.alertTitleView) as TextView
val subtitle = this.findViewById(R.id.alertSubtitleView) as TextView
val positiveButton = this.findViewById(R.id.yesBtnView) as Button
val negativeButton = this.findViewById(R.id.noBtnView) as Button
title.text = context.getString(R.string.happy_birthday)
subtitle.text = context.getString(R.string.message_change_icon)
negativeButton.let {
it.text = context.getString(R.string.ok)
it.setOnClickListener {
this.dismiss()
action.invoke()
}
}
positiveButton.gone(false)
}
show()
}
}
And use as follows in my view:
override fun showAlertChangedIcon(action: () -> Unit) {
MaterialDialog.Builder(rootView.context).alertIconInfoChanged {
MaterialDialog.Builder(rootView.context).alertChangedIcon {
action.invoke()
}
}
}
And in my controller I have the functions that direct screens
.subscribe({ response ->
when (response) {
is Result.Success -> {
viewContract.showAlertChangedIcon {
when {
...
}
else -> {
...
}
}
}

I suspect it has to do with the labeled returns.
When you call run here:
fun MaterialDialog.Builder.alertChangedIcon (action: () -> Unit) {
this.apply {
...
build().run { <----- when you call here
...
btnPosition.setOnClickListener {
this.dismiss() <----- "this" may be the builder of the dialog,
and not the dialog itself
...
Try replacing this.dismiss() with the labeled return this#apply.dismiss() so you tell Kotlin exactly what to dismiss.
I hope this helps!

Related

Handle press on volume button for certain time

How can I handle press on volume button up for 5 seconds in this override function
override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
val action = event!!.action
return when (val keyCode = event.keyCode) {
//handle press on volume up button
KeyEvent.KEYCODE_VOLUME_UP -> {
true
}
else -> super.dispatchKeyEvent(event)
}
}
I suggest using a delay on ACTION_DOWN and after the delay do your operation.
private var volumeUpJob : Job? = null
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.keyCode == KEYCODE_VOLUME_UP) {
if (event.action == ACTION_DOWN) {
if (volumeUpJob?.isActive != true) {
volumeUpJob = lifecycleScope.launch {
delay(5_000)
println("pressed for 5 sec")
// do your operation here
volumeUpJob?.cancel()
}
}
} else {
volumeUpJob?.cancel()
}
}
return super.dispatchKeyEvent(event)
}
Note that you need to cancel the job when user pull their finger up of the button. and also when we caught the 5 seconds as well.

useing shared preferences to save Button click state

i am working on comment section of an application like play store using mvvm,coroutine,kodein and DataBinding.i set login page in my main activity After the user presses the login button Comment Activity will become apparent.
I set recyclerview in comment activity. at end of every item i asked a question that was this review helpful or not. if not press no else press yes.i used shared preferences to save button state. for example when i clicked on yes button yesclicked(boolean variable) will be saved in sharedpref. till here everything works fine.
the problem--> i saved that state then i getYesButtonState() in onBindViewHolder method of recyclerview class and i said when activity recreated change the background color of yes button to #D5FFD7 for this purpose that you clicked on this before
but nothing happend and it didnt work
this code is for shared pref
val SPP_NAME = "ButtonState"
var buttonLocalState: SharedPreferences = context.getSharedPreferences(SPP_NAME, Context.MODE_PRIVATE)
fun setYesButtonState(isClicked: Boolean) {
val userLocalDatabaseEditor: SharedPreferences.Editor = buttonLocalState.edit()
userLocalDatabaseEditor.putBoolean("yesClicked", isClicked)
userLocalDatabaseEditor.apply()
}
fun setNoButtonState(isClicked: Boolean) {
val userLocalDatabaseEditor: SharedPreferences.Editor = buttonLocalState.edit()
userLocalDatabaseEditor.putBoolean("noClicked", isClicked)
userLocalDatabaseEditor.apply()
}
fun getYesButtonState(): Boolean? {
if (buttonLocalState.getBoolean("yesClicked", false) == false) {
return null
} else {
return true
}
}
fun getNoButtonState(): Boolean? {
if (buttonLocalState.getBoolean("noClicked", false) == false) {
return null
} else {
return true
}
}
fun clearButtonState() {
val userLocalDatabaseEditor: SharedPreferences.Editor = buttonLocalState.edit()
userLocalDatabaseEditor.clear()
userLocalDatabaseEditor.apply()
}
this is for recyclerview class:
//yes button clicked
yesbtn.setOnClickListener {
yesClicked = true
localStore.clearButtonState()
localStore.setYesButtonState(yesClicked)
val Helpful = 1
if (localStore.getYesButtonState() == true) {
nobtn.setBackgroundColor(Color.WHITE)
startColorAnimation(yesbtn)
activity.handler.postDelayed({
yesbtn.setBackgroundColor(Color.parseColor("#D5FFD7"))
nobtn.isClickable = true
}, 892.25.toLong())
}
try {
viewModel.deleteperson(
localStore.getUserName().toString(),
currentItem.id
).observe(mlifecycleOwner, Observer {
})
} catch (e: IllegalStateException) {
e.fillInStackTrace()
}
viewModel.feedback(
currentItem.id,
localStore.getUserName().toString(),
currentItem.description,
Helpful
).observe(mlifecycleOwner, Observer {
})
Toast.makeText(
context,
"thanks for your feedback",
Toast.LENGTH_SHORT
).show()
yesbtn.isClickable = false
}
//no button clicked
nobtn.setOnClickListener {
noClicked = true
localStore.clearButtonState()
localStore.setNoButtonState(noClicked)
val Helpful = 0
if (localStore.getNoButtonState() == true) {
yesbtn.setBackgroundColor(Color.WHITE)
startColorAnimation(nobtn)
activity.handler.postDelayed({
nobtn.setBackgroundColor(Color.parseColor("#D5FFD7"))
yesbtn.isClickable = true
}, 892.25.toLong())
}
try {
viewModel.deleteperson(
localStore.getUserName().toString(),
currentItem.id
).observe(mlifecycleOwner, Observer {
})
} catch (e: IllegalStateException) {
e.fillInStackTrace()
}
viewModel.feedback(
currentItem.id,
localStore.getUserName().toString(),
currentItem.description,
Helpful
).observe(mlifecycleOwner, Observer {
})
Toast.makeText(
context,
"please tell us why",
Toast.LENGTH_SHORT
).show()
it.isClickable = false
}
where i did wrong. thanks for your Help
try this
after the button click .. call notifyDataSetChanged(); in your adapter class

How to add animation to the viewPager in Kotlin?

**this is my Activity pager **
private const val TAG = "CarpagerActivity"
var carList: ArrayList<Car>? = null
var mSerializer : JsonSerializer? = null
class CarPagerActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_car_pager)
mSerializer = JsonSerializer("CarTrinkApp.json",
applicationContext)
try {
carList = mSerializer!!.load()
} catch (e: Exception) {
carList = ArrayList()
Log.e("Error loading cars: ", "", e)
}
// create list of fragments, one fragment for each car
var carFragmentList = java.util.ArrayList<Fragment>()
for (car in carList!!) {
carFragmentList.add(ShowCarFragment.newInstance(car))
}
val pageAdapter = CarPagerAdapter(supportFragmentManager, carFragmentList)
findViewById<ViewPager>(R.id.pager_cars).adapter = pageAdapter
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val myPost = data?.getIntExtra("adapterPosition", 123)
println(myPost)
println("adadadada")
}
class CarPagerAdapter(fm: FragmentManager, private val carFragmentList: ArrayList<Fragment>) : FragmentPagerAdapter(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getCount() = carFragmentList.size
override fun getItem(position: Int) = carFragmentList[position]
}
}
[![I want add animation to this transition ][1]][1]
**and also this page in Fragment Layout **
[1]: https://i.stack.imgur.com/qFB3b.png
Fading animation, see reference here
viewPager.setPageTransformer(false) { page, position ->
// do transformation here
page.alpha = 0f
page.visibility = View.VISIBLE
// Start Animation for a short period of time
page.animate()
.alpha(1f).duration =
page.resources.getInteger(android.R.integer.config_longAnimTime)
.toLong()
}
or
viewPager.setPageTransformer(false) { page, position ->
// do transformation here
page.rotationY = position * -70
}

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

Firebase HomeActivity not redirecting to LoginActivity [duplicate]

class LoginActivity : AppCompatActivity() {
private val firebaseAuth = FirebaseAuth.getInstance()
private val firebaseAuthListener = FirebaseAuth.AuthStateListener {
val user = firebaseAuth.currentUser?.uid
user?.let {
startActivity(HomeActivity.newIntent(this))
finish()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
loginProgressLayout.setOnTouchListener { v, event -> true }
}
fun onLogin(v: View) {
var proceed = true
if (emailET.text.isNullOrEmpty()) {
emailTIL.error = "email is required"
emailTIL.isErrorEnabled = true
proceed = false
}
if(passwordET.text.isNullOrEmpty()) {
passwordTIL.error = "password is required"
passwordTIL.isErrorEnabled = true
proceed = false
}
if(proceed){
loginProgressLayout.visibility = View.VISIBLE
firebaseAuth.signInWithEmailAndPassword(emailET.text.toString(), passwordET.text.toString())
.addOnCompleteListener { task ->
if (!task.isSuccessful){
loginProgressLayout.visibility = View.GONE
Toast.makeText(this#LoginActivity, "LoginError", Toast.LENGTH_SHORT).show()
}
}
.addOnFailureListener { exception ->
exception.printStackTrace()
loginProgressLayout.visibility = View.GONE
}
}
} //onLogin end
I checked I got something authentication number from firebaseAuth.signInWithEmailAndPassword code line.
But my question is about the property FirebaseAuth.AuthStateListener, which doesn't work.
When I get authentication number and then I want the AuthStateListener to work!
I read the Firebase API, but it didn't work. How can I make FirebaseAuth.AuthStateListener work?
You need to call addAuthStateListener with your listener in order for it to work.
So for example in the onStart of your activity:
override fun onStart() {
super.onStart()
firebaseAuth!!.addAuthStateListener(this.firebaseAuthListener!!)
}
I recommend studying this answer (more): Android Studio (Kotlin) - User has to log back into app every time app is closed

Categories

Resources