I have this setOnClickListener that first check if the user logged in then if the user logged in will run the function as below:
like.setOnClickListener {
val sharedPreference2 = context?.getSharedPreferences("isLogin", Context.MODE_PRIVATE)
val fbtoken = sharedPreference2?.getString("UserToken", "false")
if(fbtoken.equals("false"))
{
val builder = AlertDialog.Builder(context).create()
val optionDialog = AlertDialog.Builder(context)
val layoutInflator = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val dialogView = layoutInflator.inflate(R.layout.alert_reg, null)
val goreg = dialogView.findViewById<TextView>(R.id.confirmation_reg)
val cancel = dialogView.findViewById<TextView>(R.id.cancel_reg)
builder.setCancelable(false)
builder.setView(dialogView)
goreg?.setOnClickListener {
val intent = Intent(context, SignupActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
cancel?.setOnClickListener {
builder.dismiss()
}
builder.show()
}
else
{
postLike(position, it.context)
like.setImageResource(R.drawable.liked)
}
}
So the this setOnClickListener first will check the login and in "else" will post in API.
I'm trying to use same setOnClickListener used above if the user click again , it will delete it from API
I tried to replace "else" with "if" and "else" like the code below:
if (fbtoken.equals("true")){
postLike(position, it.context)
like.setImageResource(R.drawable.liked)
}else{
like.setImageResource(R.drawable.like)
deleteLike(position, it.context)
}
But now it delete it from API only
Its something similar to IG like button if I click first time the button it will post the like and if I click again it will delete it.
What am I doing wrong here?
Correct way would be, not to call setImageResouce everytime user clicks on the image but have selector which would have two states like this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_address_item_bg"android:state_selected="false"/>
<item android:drawable="@drawable/ic_selected_address_bg"
android:state_selected="true"/>
<item android:drawable="@drawable/ic_selected_address_bg" />
</selector>
you should set this xml as src parameter of image view or whataver view it is .
after that you should change state of view respectively according to user action
likeButton.setonCLickListener {
it.isSelected = !it.isSelected
if (it.isSelected) {
postLike()
} else {
postUnlike()
}
}