How to increment counter of notification badge from adapter kotlin - android

I am trying to build an E-commerce app having basic functionalities. I want my number of items in the cart to reflect on the action bar. Currently, my UI looks like this.
For creating the notifications this is what I have done:
cart_layout.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="55sp"
android:paddingRight="10sp"
android:gravity="center">
<ImageView
android:id="#+id/cart_img"
android:layout_width="30sp"
android:layout_height="30sp"
android:background="#drawable/shopping"
android:foreground="?attr/selectableItemBackgroundBorderless" />
<TextView
android:id="#+id/item_count"
android:layout_width="18sp"
android:textAlignment="center"
android:layout_height="18sp"
android:textColor="#android:color/white"
android:text="0"
android:textSize="12sp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="21dp"
android:layout_marginTop="5dp"
android:background="#drawable/itemcount" />
</RelativeLayout>
</RelativeLayout>
My cart_menu.xml inside the menu directory looks like:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/select_cart"
app:showAsAction="always"
app:actionLayout="#layout/cart_layout"
android:title="Cart"/>
<item android:id="#+id/toolbar_search"
android:title="Search"
android:icon="#drawable/ic_search_black_24dp"
app:showAsAction ="always"
app:actionViewClass="android.widget.SearchView"/>
</menu>
My onCreateOptionsMenu functions inside Activity looks like this:
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.cart_menu, menu)
val count:View = menu!!.findItem(R.id.select_cart).actionView
val itemText:TextView = count.findViewById(R.id.item_count)
if(cartList.size == 0){
itemText.visibility = View.INVISIBLE
}
if(cartList.size > 0) {
itemText.visibility = View.VISIBLE
itemText.text = cartList.size.toString()
}
return true
}
Here cartList is the MutableList of items in the cart.
What I want to do is update the counter of this cart whenever the user clicks "Add to cart" button.
The click listener for this button is present inside Adapter class.
My onclicklistener inside onBindViewHolder inside ProductAdapter.kt looks like this:
holder.addToCart.setOnClickListener {
holder.count.number = 1.toString()
Log.d("Product","Clicked ${product.name}, count = ${holder.count.number}")
val cartItemObj = CartItem(product.name,product.imageUrl, product.size, product.price, holder.count.number)
val db = CartDatabase(context)
val result = db.insertData(cartItemObj)
if(result == (-1).toLong()){
Log.d("ProductAdapter","Error in Inserting values")
return#setOnClickListener
}
holder.addToCart.visibility = View.INVISIBLE
holder.count.visibility = View.VISIBLE
cartList.add(cartItemObj)
// SOME CODE HERE TO UPDATE THE NUMBER OF ITEMS IN CART
}
I don't understand how should I achieve this since I am unable to access the Textview inside the Adapter.
The link to the complete project is:
Here

Define cart count
var cartCounter: Int? = 0
//private lateinit var itemText: TextView
lateinit var itemText: TextView
Then Update it in onCreateOptionsMenu method
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.cart_menu, menu)
val count:View = menu!!.findItem(R.id.select_cart).actionView
itemText:TextView = count.findViewById(R.id.item_count)
if(cartList.size == 0){
itemText.visibility = View.INVISIBLE
}
if(cartList.size > 0) {
cartCounter = cartList.size;
itemText.visibility = View.VISIBLE
itemText.text = cartCounter.toString()
}
return true
}
Finally when user click on add to cart update it again
holder.addToCart.setOnClickListener {
holder.count.number = 1.toString()
val cartItemObj = CartItem(product.name,product.imageUrl, product.size, product.price, holder.count.number)
val db = CartDatabase(context)
val result = db.insertData(cartItemObj)
if(result == (-1).toLong()){
Log.d("ProductAdapter","Error in Inserting values")
return#setOnClickListener
}
holder.addToCart.visibility = View.INVISIBLE
holder.count.visibility = View.VISIBLE
cartList.add(cartItemObj)
cartCounter = cartCounter + 1;
// or cartCounter = cartCounter + quantity_of_item;
itemText.text = cartCounter.toString()
}

I am unable to access the Textview inside the Adapter
Your adapter should not know anything about the menu and its items. But it can expose some observable field which can be monitored by an entity owning the menu - I guess it is either your Fragment or Activity. The easiest way to achieve this nowadays is by using LiveData. Create a new instance of it somewhere in your adapter:
class YourAdapter ... {
val cartSize = MutableLiveData<Int>()
}
and update it from your click listener. Now you can observe this livedata from your fragment like this
override fun onViewCreated(...) {
adapter.cartSize.observe(viewLifecycleOwner, Observer {
cartSize -> updateMenuCounter(cartSize)
}
}
The last step here is to implement the updateMenuCounter which can access the previously created MenuItem and update its TextView.

Related

How to use MutableStateFlow to search item in list

I am learning kotlin flow in android. I want to basically instant search in my list and filter to show in reyclerview. I searched in google and found this amazing medium post. This post is basically search from google. I want to search item in list and show in reyclerview. Can someone guide me how can I start this. I am explanning in more detail
Suppose I have one SearchBox and one Reyclerview which one item abc one, abc two, xyz one, xyz two... etc.
main image when all data is combine
Scenario 1
when I start typing in SearchBox and enter small a or capital A I want to show only two item matching in recyclerview, look like this
Scenario 2
when I enter any wrong text in SearchBox I want to basically show a text message that not found, look like this
Any guidance would be great. Thanks
I am adding my piece of code
ExploreViewModel.kt
class ExploreViewModel(private var list: ArrayList<Category>) : BaseViewModel() {
val filteredTopics = MutableStateFlow<List<opics>>(emptyList())
var topicSelected: TopicsArea? = TopicsArea.ALL
set(value) {
field = value
handleTopicSelection(field ?: TopicsArea.ALL)
}
private fun handleTopicSelection(value: TopicsArea) {
if (value == TopicsArea.ALL) {
filterAllCategories(true)
} else {
filteredTopics.value = list.firstOrNull { it.topics != null && it.title == value.title }
?.topics?.sortedBy { topic -> topic.title }.orEmpty()
}
}
fun filterAllCategories(isAllCategory: Boolean) {
if (isAllCategory && topicSelected == TopicsArea.ALL && !isFirstItemIsAllCategory()) {
list.add(0, code = TopicsArea.ALL.categoryCode))
} else if (isFirstItemIsAllCategory()) {
list.removeAt(0)
}
filteredTopics.value = list.flatMap { it.topics!! }.distinctBy { topic -> topic.title }.sortedBy { topic -> topic.title }
}
private fun isFirstItemIsAllCategory() = list.firstOrNull()?.code == TopicsArea.ALL
}
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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="16dp"
app:closeIcon="#drawable/ic_cancel"
app:layout_constraintBottom_toTopOf="#+id/exploreScroll"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:layout_constraintVertical_chainStyle="packed" />
<HorizontalScrollView
android:id="#+id/exploreScroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:scrollbars="none"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/searchView">
<com.google.android.material.chip.ChipGroup
android:id="#+id/exploreChips"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:chipSpacingHorizontal="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:singleLine="true"
app:singleSelection="true" />
</HorizontalScrollView>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/exploreList"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="20dp"
android:paddingTop="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_default="wrap"
app:layout_constraintVertical_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/exploreScroll" />
</androidx.constraintlayout.widget.ConstraintLayout>
Category.kt
#Parcelize
data class Category(
val id: String? = null,
val title: String? = null,
val code: String? = null,
val topics: List<Topics>? = null,
) : Parcelable
Topics.kt
#Parcelize
data class Topics(
val id: String? = null,
val title: String? = null
) : Parcelable
Dummy data and coming from server
fun categoriesList() = listOf(
Categories("21", "physical", listOf(Topics("1", "Abc one"), Topics("2", "Abc Two"))),
Categories("2211", "mind", listOf(Topics("1", "xyz one"), Topics("2", "xyz two"))),
Categories("22131", "motorized", listOf(Topics("1", "xyz three"), Topics("2", "xyz four"))),
)
In my view model list is holding above dummy data. And In my recyclerview I am passing the whole object and I am doing flatMap to combine all data into list. Make sure In recyclerview is using Topic and using title property. In Image Abc one, Abc two is holding in Topic. Thanks
After #Tenfour04 suggestion I will go to A2 suggestion because I have already data which converted into flow and passing in my adapter. I am adding my activity code as well.
ExploreActivity.kt
class ExploreActivity : AppCompatActivity() {
private val binding by lazy { ExploreLayoutBinding.inflate(layoutInflater) }
val viewModel by viewModel<ExploreViewModel> {
val list = intent?.getParcelableArrayListExtra(LIST_KEY) ?: emptyList<Category>()
parametersOf(list)
}
var exploreAdapter = ExploreAdapter { topic -> handleNextActivity(topic) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
setupView()
}
fun setupView() {
setupSearchView()
setupFilteredTopic()
setupExploreAdapter()
}
private fun setupFilteredTopic() {
lifecycleScope.launchWhenCreated {
repeatOnLifecycle(Lifecycle.State.CREATED) {
viewModel.filteredTopics.collect { filteredTopicsList ->
exploreAdapter.submitList(filteredTopicsList)
}
}
}
}
fun setupSearchView() {
binding.searchView.apply {
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?) = false
override fun onQueryTextChange(newText: String?): Boolean {
return true
}
})
}
}
fun setupExploreAdapter() {
with(binding.exploreList) {
adapter = exploreAdapter
}
}
}
UPDATE 2
ExploreViewModel.kt
val filteredCategories = query
.debounce(200) // low debounce because we are just filtering local data
.distinctUntilChanged()
.combine(filteredTopics) { queryText, categoriesList ->
val criteria = queryText.lowercase()
if (criteria.isEmpty()) {
return#combine filteredTopics
} else {
categoriesList.filter { category -> category.title?.lowercase()?.let { criteria.contains(it) } == true }
}
}
I am getting error when I set in adapter
fixed
filteredTopics.value
The tutorial you linked has a Flow produced by the SearchView. If you want to keep the search functionality in your ViewModel, you can put a MutableStateFlow in your ViewModel that will be updated by the SearchView indirectly. You can expose a property for updating the query.
There are two different ways this could be done, depending on whether you (A) already have a complete list of your data that you want to query quickly or (B) you want to query a server or your database every time your query text changes.
And then even (A) can be broken up into: (A1) you have a static plain old List, or (A2) your source List comes from a Flow, such as a returned Room flow that is not based on query parameters.
All code below is in the ViewModel class.
A1:
private val allCategories = categoriesList()
private val query = MutableStateFlow("")
// You should add an OnQueryTextListener on your SearchView that
// sets this property in the ViewModel
var queryText: String
get() = query.value
set(value) { query.value = value }
// This is the flow that should be observed for the updated list that
// can be passed to the RecyclerView.Adapter.
val filteredCategories = query
.debounce(200) // low debounce because we are just filtering local data
.distinctUntilChanged()
.map {
val criteria = it.lowercase()
allCategories.filter { category -> criteria in category.title.lowercase }
}
A2:
In this example I put a simple placeholder flow for the upstream server query. This could be any flow.
private val allCategories = flow {
categoriesList()
}
private val query = MutableStateFlow("")
// You should add an OnQueryTextListener on your SearchView that
// sets this property in the ViewModel
var queryText: String
get() = query.value
set(value) { query.value = value }
// This is the flow that should be observed for the updated list that
// can be passed to the RecyclerView.Adapter.
val filteredCategories = query
.debounce(200) // low debounce because we are just filtering local data
.distinctUntilChanged()
.combine(allCategories) { queryText, categoriesList ->
val criteria = queryText.lowercase()
categoriesList.filter { category -> criteria in category.title.lowercase }
}
B
private val query = MutableStateFlow("")
// You should add an OnQueryTextListener on your SearchView that
// sets this property in the ViewModel
var queryText: String
get() = query.value
set(value) { query.value = value }
// This is the flow that should be observed for the updated list that
// can be passed to the RecyclerView.Adapter.
val filteredCategories = query
.debounce(500) // maybe bigger to avoid too many queries
.distinctUntilChanged()
.map {
val criteria = it.lowercase()
categoriesList(criteria) // up to you to implement this depending on source
}

How to reverse View Binding from custom tab layout in Android?

I made a custom tab item for my tab layout and initialized it using view binding as follows:
val tabView = CustomTabBinding.inflate(LayoutInflater.from(mContext), null, false)
tabView.tvCustomTabTitle.text = it.title
tabView.tvCustomTabCount.visibility = View.GONE
Now when the user selects/unselects the tab I want to change the appearance of this custom view. Usually I achieved this using kotlin synthetics as follows:
fun setOnSelectView(tabLayout: TabLayout, position: Int = 0) {
val tab = tabLayout.getTabAt(position)
val selected = tab?.customView
if (selected != null)
selected.tv_custom_tab_title?.apply {
setTextColor(mContext.getColorCompat(R.color.colorAccent))
typeface = setFont(true)
}
selected?.tv_custom_tab_count?.apply {
setBackgroundResource(R.drawable.bullet_accent)
mContext.getColorCompat(android.R.color.white)
}
}
But now how do I achieve this using view binding?
I am using the method of findViewById():
fun Context.setOnSelectView(tabLayout: TabLayout, position: Int = 0) {
val tab = tabLayout.getTabAt(position)
val selected = tab?.customView
if (selected != null){
val title = selected.findViewById<TextView>(R.id.tv_custom_tab_title)
val count = selected.findViewById<TextView>(R.id.tv_custom_tab_count)
title.apply {
setTextColor(getColorCompat(R.color.colorAccent))
typeface = setFont(true)
}
count.apply {
setBackgroundResource(R.drawable.bullet_accent)
getColorCompat(android.R.color.white)
}
}
}
but I am hoping there is a better way to do this. If yes, then please do help me out.
Late reply but this is how I used view binding for custom tab layout, hope it helps
custom_tab.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tv_custom_tab_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/tv_custom_tab_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
your activity/fragment:
val tab = binding.tabLayout.getTabAt(position)
tab.setCustomView(R.layout.custom_tab)
val tabBinding = tab.customView?.let {
CustomTabBinding.bind(it)
}
tabBinding?.tvCustomTabTitle?.text = "your title here"

switchbox change state on rotation

I develop a simple table-app, and the problem is, that the switch-box will change the state or doesn't reset the state correcly on change rotation.
befor rotating it looks like
this
after rotating it looks like
this
The hint state will set correct on change but the box is not displayed correctly. What has gone wrong? Actually the views should be updated on any changes in the same way...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Switch
android:id="#+id/tv_outputItemBoolean"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:trackTint="#color/switch_track_selector"
android:thumbTint="#color/switch_thumb_selector"
android:clickable="true"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingBottom="2.5dp"
android:paddingTop="2.5dp"
android:textSize="20sp"
android:gravity="center"
/>
</LinearLayout>
fun getView(position: Int, rowView: TableRow?, parent: TableLayout): TableRow {
val rowView = TableRow(parent!!.context)
val rowData = this.getItem(position)
for (i in 0..columnCounts - 1) {
var data: ColumnData<*>? = rowData[i]
rowView.addView(this.getColumnView(data, null, rowView))
}
return rowView
}
private fun getColumnView(
col: ColumnData<*>?,
resycleView: View?,
parent: ViewGroup
): View {
return when (col?.type) {
DataType.TimeStamp -> {
val view = TimeStampPicker.View(parent.context)
view.timeStampPicker.timeStampInMillis = col.data as Long
view
}
DataType.Boolean ->
{
val c= parent.context
val view =
LayoutInflater.from(c)
.inflate(R.layout.output_item_boolean, null)
val switch: Switch = view.findViewById(R.id.tv_outputItemBoolean)
val value = col.data as Boolean
var state = switch.isChecked
Log.v("XXXXXXXXXXXXXXXX", value.toString()+","+state.toString())
switch.isChecked=value
state = switch.isChecked
Log.v("XXXXXXXXXXXXXXXX", value.toString()+","+state.toString())
switch.hint=c.getText(DataType.stringResourceOf(value))
view
}
else -> {
val view =
LayoutInflater.from(parent.context)
.inflate(R.layout.ouput_item_simple_text, null)
val tv: TextView = view.findViewById(R.id.tv_outputItemSimpleText)
tv.text = if (col != null) col.data.toString() else "NULL"
view
}
}
}
the output log print shows the right state befor and after setting.
V/XXXXXXXXXXXXXXXX: false,false
V/XXXXXXXXXXXXXXXX: false,false
V/XXXXXXXXXXXXXXXX: true,false
V/XXXXXXXXXXXXXXXX: true,true
V/XXXXXXXXXXXXXXXX: true,false
V/XXXXXXXXXXXXXXXX: true,true
V/XXXXXXXXXXXXXXXX: false,false
V/XXXXXXXXXXXXXXXX: false,false

Android: Enable a Button inside RecyclerView.ViewHolder

I have a button (id: readyButtonIntro) inside a layout (introscreen.xml) that i need to enable. To do that, i have another button inside the RecyclerView.ViewHolder.
This is my Layout to need access
introscreen.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"
android:background="#color/colorWhite"
tools:context=".IntroScreenVC">
<LinearLayout
android:id="#+id/indicatorContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
android:gravity="center"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent" />
<Button
android:id="#+id/readyButtonIntro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:background="#color/colorWhite"
android:textColor="#color/colorTerciary"
android:alpha="0"
android:enabled="false"
android:text="Ready"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
And the another button is inside into the ViewHolder
slide_item_container.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="15dp"
>
<Button
android:id="#+id/addData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Agregar Datos"
android:background="#drawable/button_rounded2"
/>
</LinearLayout>
How can I enable from inside the class that listener the button?
class IntroSlideViewHolder(view: View) : RecyclerView.ViewHolder(view) {
init {
addData.setOnClickListener(View.OnClickListener {
//NEED TO ENABLE THE BUTTON
// val introScreen = IntroScreenVC()
// introScreen.readyButton()
}
}
I have a fun into IntroScreenVC but always have a error that its null, if a pass the context or view, do nothing.
fun readyButton(){
readyButtonIntro.isEnabled = true
}
Could you help me with this? I would really appreciate it.
Thank you very much!
Regards.
Edit:
I put the adapter and the ViewHolder for more information.
I ignored that because I didn't want to create confusion. Sorry for that..
Class Constructor
data class IntroSlide(val title: String, val description: String, val icon: Int, val firstButton: Boolean, val secondButton: Boolean, val thirdButton: Boolean)
IntroScreenVC.kt
class IntroScreenVC: AppCompatActivity() {
private val introSliderAdapter = IntroScreenAdapter(
listOf(
IntroSlide(
"title1",
"description1",
R.drawable.logo,
false,
false,
false
),
IntroSlide(
"title2",
"description2",
R.drawable.doggrooming,
true,
false,
false
),
IntroSlide(
"title3",
"description3",
R.drawable.introscreen3,
false,
true,
false
)
)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.introscreen)
introSliderViewPager.adapter = introSliderAdapter
}
}
IntroScreenAdapter.kt
class IntroScreenAdapter(private val introSlides: List<IntroSlide>) : RecyclerView.Adapter<IntroSlideViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IntroSlideViewHolder {
val layoutInflater = LayoutInflater.from(parent?.context)
val cellForRow = layoutInflater.inflate(R.layout.slide_item_container,parent,false)
return IntroSlideViewHolder(cellForRow)
}
override fun getItemCount(): Int {
return introSlides.size
}
override fun onBindViewHolder(holder: IntroSlideViewHolder, position: Int) {
holder.bind(introSlides[position])
}
}
class IntroSlideViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val textTitle = view.findViewById<TextView>(R.id.textTitle)
private val textDescription = view.findViewById<TextView>(R.id.textDescription)
private val imageIcon = view.findViewById<ImageView>(R.id.imageSlideIcon)
private val addData = view.findViewById<Button>(R.id.addData)
private val addPet = view.findViewById<Button>(R.id.agregarMascota)
val contexto = itemView.context;
fun bind(introSlide: IntroSlide) {
textTitle.text = introSlide.title
textDescription.text = introSlide.description
imageIcon.setImageResource(introSlide.icon)
addData.isEnabled = introSlide.firstButton
addPet.isEnabled = introSlide.thirdButton
}
}
init {
addData.setOnClickListener(View.OnClickListener {
//ADD A ALERTDIALOG AND WHEN PRESS OK NEED TO ENABLE THAT BUTTON
val mDialogView = LayoutInflater.from(contexto).inflate(R.layout.alertdialog_add_data,null)
val builder = AlertDialog.Builder(contexto)
builder.setView(mDialogView)
val dialog: AlertDialog = builder.create()
dialog.show()
dialog.getWindow()?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT));
mDialogView.agregarDatosOK.setOnClickListener {
//HERE I NEED TO ENABLE THE BUTTON
//readyButtonIntro(introscreen.xml)
}
}
}
Edit2:
This is what I do with sharedPreferences.
IntroScreenAdapter.kt
class IntroSlideViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val textTitle = view.findViewById<TextView>(R.id.textTitle)
private val textDescription = view.findViewById<TextView>(R.id.textDescription)
private val imageIcon = view.findViewById<ImageView>(R.id.imageSlideIcon)
private val addData = view.findViewById<Button>(R.id.addData)
private val addPet = view.findViewById<Button>(R.id.agregarMascota)
//INIT sharedPreferences
private val prefs: SharedPreferences = view.context.getSharedPreferences(getString(R.string.prefs_file), Context.MODE_PRIVATE)
val contexto = itemView.context;
fun bind(introSlide: IntroSlide) {
textTitle.text = introSlide.title
textDescription.text = introSlide.description
imageIcon.setImageResource(introSlide.icon)
addData.isEnabled = introSlide.firstButton
addPet.isEnabled = introSlide.thirdButton
}
}
init {
addData.setOnClickListener(View.OnClickListener {
val mDialogView = LayoutInflater.from(contexto).inflate(R.layout.alertdialog_add_data,null)
val builder = AlertDialog.Builder(contexto)
builder.setView(mDialogView)
val dialog: AlertDialog = builder.create()
dialog.show()
dialog.getWindow()?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT));
mDialogView.agregarDatosOK.setOnClickListener {
//HERE EDIT THE sharedPreferences
with (prefs.edit()) {
putBoolean("ready_button_enabled", true)
apply()
}
dialog.dismiss()
}
}
}
IntroScreenVC.kt
class IntroScreenVC: AppCompatActivity() {
private val introSliderAdapter = IntroScreenAdapter(
listOf(
IntroSlide(
"title1",
"description1",
R.drawable.logo,
false,
false,
false
),
IntroSlide(
"title2",
"description2",
R.drawable.doggrooming,
true,
false,
false
),
IntroSlide(
"title3",
"description3",
R.drawable.introscreen3,
false,
true,
false
)
)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.introscreen)
introSliderViewPager.adapter = introSliderAdapter
}
//HERE PUT THE RESUME TO EXPECT THE SHOW AND ENABLE THE BUTTON
override fun onResume() {
super.onResume()
val prefs = getSharedPreferences(getString(R.string.prefs_file), Context.MODE_PRIVATE)
val buttonEnabled = prefs.getBoolean("ready_button_enabled", false)
readyButtonIntro.isEnabled = buttonEnabled
if (buttonEnabled) {
readyButtonIntro.alpha = 1f
}else {
readyButtonIntro.alpha = 0f
}
}
}
SOLUTION:
Into the Activity (IntroScreenVC)
class IntroScreenVC: AppCompatActivity(), IntroScreenAdapter.AdapterOnClick {
private val introSliderAdapter =
listOf(
...
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.introscreen)
introSliderViewPager.adapter = IntroScreenAdapter(introSliderAdapter, this)
}
...
override fun onClick() {
//HERE ENABLE AND SHOW THE BUTTON
readyButtonIntro.isEnabled = true
readyButtonIntro.alpha = 1f
}
And the into the Adapter and RecyclerView
class IntroScreenAdapter(private val introSlides: List<IntroSlide>, val adapterOnClick: AdapterOnClick) : RecyclerView.Adapter<IntroScreenAdapter.IntroSliderViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IntroScreenAdapter.IntroSliderViewHolder {
val layoutInflater = LayoutInflater.from(parent?.context)
val cellForRow = layoutInflater.inflate(R.layout.slide_item_container,parent,false)
return IntroSliderViewHolder(cellForRow)
}
...
inner class IntroSliderViewHolder(view: View) : RecyclerView.ViewHolder(view) {
...
init {
addData.setOnClickListener(View.OnClickListener {
val mDialogView = LayoutInflater.from(contexto).inflate(R.layout.alertdialog_add_data,null)
val builder = AlertDialog.Builder(contexto)
builder.setView(mDialogView)
val dialog: AlertDialog = builder.create()
dialog.show()
dialog.getWindow()?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT));
mDialogView.agregarDatosOK.setOnClickListener {
//FINALLY HERE CHANGE THE BUTTON TO ENABLE :)
adapterOnClick.onClick()
}
}
}
}
As I understand your problem you have a class A that is trying to communicate (change something) in class B.
There are several options for solving this kind of problem, depending on your exact needs.
From the code you have provided the relation of your Layouts and classes is not clear enough to me to give a more precise answer.
First of all, I understand you are using a recycler view.
A recycler view can have many items, and I assume you want to be able to enable that button from each item.
In order to let your IntroScreen class communicate with your viewholder, you have to pass a reference to the ViewHolder constructor.
For this purpose you could implement a simple "callback pattern".
Here is an example for defining an interface (e.g. for a function that enables the button) and implementing the callback.
Have a read here to see a well-explained example in Java. In Kotlin you could do it the same way.
Here a summary of the implementation steps:
define interface EnableButtonCallback that implements an abstract method enableButton
let your InfoScreen class implement that interface (in which you enable the button)
pass your InfoScreen class to your RecyclerView adapter and then from your adapter to your ViewHolder
in your ViewHolder onClickListener call the interface method enableButton
Update 2020/08/11
I try to give suggestions based on your updated code.
In the intro screen you set your viewPager adapter, but it is still not clear where this property is coming from and where exactly it is displayed. I guess maybe you just cut out the parameter definition. However, I just assume you have your views set up properly and this is not a problem here. For using recycler view with viewPager I found some related information here.
I can not yet see your use case clearly yet. Are you adding data persistently? Then should your button in the IntroScreen be permanently enabled?
In this case probably SharedPreferences are a good choice for persisting this kind of information. Even when it doesn't need to be persisted. Reading one shared preference file is lightweight and quick enough to be done on the main thread.
I will give you an example implementation here:
Get a shared preferences object
val sharedPref = activity?.getSharedPreferences(
"intro_button_settings_file", Context.MODE_PRIVATE) // String with the key should be in your string resource file
Pass your sharedPref to your adapter and your viewHolder and write to it:
with (sharedPref.edit()) {
putBoolean("ready_button_enabled", true) // String with the key should be in your string resource file
commit()
}
in your IntroScreen check the setting
val readyButtonShouldBeEnabled = sharedPref.getBoolean("ready_button_enabled",
false) // defaults to false
If, after clicking your enable button (that sets the setting to true), you need to return to your IntroScreen activity: then you could enable your button in your activities onResume method
A different solution would be:
You check the setting in your IntroScreen onClick method.
Then you don't need to disable the button.
You just set:
// in your IntroScreen readyButtonIntro onClick method
val buttonEnabled = sharedPref.getBoolean("ready_button_enabled",
false)
if (!buttonEnabled) {
// optional: write a Toast to notify the user why the button is doing nothing (yet)
Toast.makeText(yourIntroScreenContext, "First agregar datos", Toast.LENGTH_SHORT).show()
return // onClick returns, so nothing else will happen when clicked
}
... // your code when the button **should** be enabled
If your button should be disabled again, simply save false to the setting.
Since I do not know more about your use case, this seems like an easy and quick solution to me. This way you do not need to bother with implementing an interface. Anyways, when clicking your button in your viewHolder there is no immediate action taking place in your IntroScreen activity. You still want the user to return to the IntroScreen and click the enabled button.
Then checking if your button was enabled just when clicking on it appears sufficient to me.

How to use anko spinner?

I'm trying to add a spinner inside an alert using anko. My code so far looks like this:
alert(getString(R.string.alert)) {
positiveButton("Cool") { toast("Yess!!!") }
customView {
linearLayout {
textView("I'm a text")
padding = dip(16)
orientation = LinearLayout.VERTICAL
spinner(R.style.Widget_AppCompat_Spinner) {
id = R.id.spinner_todo_category
prompt = "Select a Category"
}
}
}
}.show()
but I get compilation errors because apparently that's not how to call a spinner. I've been looking at the docs (Anko GitHub Wiki) but it says nothing about spinners.
Thanks in advance
One solution :
class AddActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val items = listOf(Friend("bla","bla",50),Friend("bla","bla",50));
val adapterFriends = ArrayAdapter(this,R.layout.mon_spinner,items)
verticalLayout {
val friends = spinner { adapter = adapterFriends }
val wine = editText()
button("Say Hello") {
onClick { toast("Hello, ${wine.text}!") }
}
}
}
}
with this layout (mon_spinner.xml) :
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#color/colorPrimary"
android:spinnerMode="dialog"
android:text="XXX"
/>
It's all right !!
Try this in your AnkoComponent:
spinner {
adapter = ArrayAdapter.createFromResource(
ctx,
R.array.your_string_array,
android.R.layout.simple_spinner_dropdown_item)
}

Categories

Resources