If the user presses the positive button, they want to move it to MainActivity
fun setPositiveButtonClick(callback: (() -> Unit)?, view: View? = null) {
val intent = Intent(this#ErrorDialog, MainActivity::class.java)
startActivity(intent)
var view = view
if (view == null) view = this.view
this.positiveCallback = callback
view?.let { v ->
v.yes.setOnClickListener {
callback?.let { c ->
c()
}
dismiss()
}
}
}
Here is the error
I'm assuming this is in some sort of Dialog class, so I think you simply need to get the context of it by just replacing
val intent = Intent(this#ErrorDialog, MainActivity::class.java)
to
val intent = Intent(this.context, MainActivity::class.java)
Related
I have an image button in my recylerview and when users click it, I want a dialog box to pop up and allow the user to edit the data in the reyclerview and save the changes.
My Adapter code
class Adapter(private var records: ArrayList<AudioRecord>, var listener: OnItemClickListener) : RecyclerView.Adapter<Adapter.ViewHolder>() {
private var editMode = false
fun isEditMode() :Boolean{return editMode}
#SuppressLint("NotifyDataSetChanged")
fun setEditMode(mode: Boolean){
if(editMode != mode){
editMode = mode
notifyDataSetChanged()
}
}
inner class ViewHolder(val binding: ItemviewLayoutBinding): RecyclerView.ViewHolder(binding.root ), View.OnClickListener, View.OnLongClickListener{
private var tvFileName : TextView = itemView.findViewById(R.id.tvFilename)
private var tvMeta : TextView = itemView.findViewById(R.id.tvMeta)
var checkbox : CheckBox = itemView.findViewById(R.id.checkBox)
val editBtn: ImageButton = itemView.findViewById(R.id.btnEdit)
init {
itemView.setOnClickListener(this)
itemView.setOnLongClickListener(this)
}
fun binding (audioRecord: AudioRecord) {
tvFileName.text = audioRecord.filename
tvMeta.text = audioRecord.duration
// checkbox.text = audioRecord.
}
override fun onClick(p0: View?) {
val position = adapterPosition
if(position != RecyclerView.NO_POSITION)
listener.onItemClickListener(position)
}
override fun onLongClick(p0: View?): Boolean {
val position = adapterPosition
if(position != RecyclerView.NO_POSITION)
listener.onItemLongClickListener(position)
return true
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(ItemviewLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
#SuppressLint("SetTextI18n", "SimpleDateFormat")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
if (position != RecyclerView.NO_POSITION){
val record: AudioRecord = records[position]
val sdf = SimpleDateFormat("dd/MM/yyyy")
val date = Date(record.timestamp)
val strDate = sdf.format(date)
holder.binding.tvFilename.text = record.filename
holder.binding.tvMeta.text = "${record.duration} $strDate"
if(editMode){
holder.checkbox.visibility = View.VISIBLE
holder.checkbox.isChecked = record.isChecked
holder.editBtn.visibility = View.GONE
}else{
holder.checkbox.visibility = View.GONE
holder.checkbox.isChecked = false
holder.editBtn.visibility = View.VISIBLE
}
holder.binding.btnEdit.setOnClickListener {
}
}
}
override fun getItemCount(): Int {
return records.size
}
}
Summary
When users click image button. Input dialog pops up
User must be able to edit data in recyclerview and save it.
change class like this inner class ViewHolder(val binding: ItemviewLayoutBinding), var imageListener:(position:Int)->Unit)
where you call adapter , use imageListener function. Whatever you want to do you can do it inside this function. Then call it in your adapter.
in init
editBtn.setOnClickListener {
imageListener(adapterPosition)
}
i'm a beginner in android & kotlin and i'm having an issue i been trying to figure out all day...
I have an app that fetches data from NewsApi and displays it in a recycler view , i am using Retrofit library and Room (to save favorite articles) with MVVM architecture. I want to add an option so that the user can select the country of the news from a dialog that pops up by clicking on a icon on the toolbar menu.
I have created a custom DialogFragment and have it show up, the dialog contains a spinner with a list of countries and i'm using FragmentResult and FragmentResultListener to pass the country value between dialog fragment and news fragment.
DialogFragment
class CountrySelectDialog : DialogFragment(R.layout.country_selection_dialog) {
private lateinit var binding: CountrySelectionDialogBinding
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = CountrySelectionDialogBinding.bind(view)
binding.spCountrySelection.onItemSelectedListener =
object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
adapterView: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
Toast.makeText(
context,
"you selected ${adapterView?.getItemAtPosition(position).toString()}",
Toast.LENGTH_SHORT
).show()
}
override fun onNothingSelected(adapterView: AdapterView<*>?) {
}
}
binding.btnCancel.setOnClickListener {
this.dismiss()
}
binding.btnConfirm.setOnClickListener {
val result = binding.spCountrySelection.selectedItem.toString()
setFragmentResult("countryCode", bundleOf("bundleKey" to result))
this.dismiss()
}
}
}
The news Fragment is observing data from the View Model
class BreakingNewsFragment : Fragment(R.layout.fragment_breaking_news) {
lateinit var viewModel: NewsViewModel
lateinit var newsAdapter: NewsAdapter
private lateinit var binding: FragmentBreakingNewsBinding
val TAG = "BreakingNewsFragment"
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentBreakingNewsBinding.bind(view)
viewModel = (activity as NewsActivity).viewModel
setUpRecyclerView()
setFragmentResultListener("countryCode") { countryCode, bundle ->
val result = bundle.getString("countryCode")
viewModel.countryCode = result!!}
viewModel.breakingNews.observe(viewLifecycleOwner, Observer {
when (it) {
is Resource.Success -> {
hideProgressBar()
it.data?.let {
newsAdapter.differ.submitList(it.articles.toList())
val totalPages = it.totalResults / QUERY_PAGE_SIZE + 2
isLastPage = viewModel.breakingNewsPage == totalPages
}
}
is Resource.Error -> {
hideProgressBar()
it.message?.let {
Log.e(TAG, "An error occurred: $it")
}
}
is Resource.Loading -> {
showProgressBar()
}
}
})
newsAdapter.setOnItemClickListener {
val bundle = Bundle().apply {
putSerializable("article", it)
}
findNavController().navigate(
R.id.action_breakingNewsFragment_to_articleFragment, bundle
)
}
}
ViewModel:
class NewsViewModel(val newsRepository: NewsRepository, val app: Application) : AndroidViewModel(app) {
val breakingNews: MutableLiveData<Resource<NewsResponse>> = MutableLiveData()
var breakingNewsPage = 1
var breakingNewsResponse: NewsResponse? = null
val searchNews: MutableLiveData<Resource<NewsResponse>> = MutableLiveData()
var searchNewsPage = 1
var searchNewsResponse: NewsResponse? = null
var countryCode :String = "it"
init {
getBreakingNews(countryCode)
}
fun getBreakingNews(countryCode: String) {
viewModelScope.launch {
breakingNews.postValue(Resource.Loading())
val response = newsRepository.getBreakingNews(countryCode, breakingNewsPage)
breakingNews.postValue(handleBreakingNewsResponse(response))
}
}
fun handleBreakingNewsResponse(response: Response<NewsResponse>): Resource<NewsResponse> {
if (response.isSuccessful) {
response.body()?.let { resultResponse ->
breakingNewsPage++
if (breakingNewsResponse == null) {
breakingNewsResponse = resultResponse
} else {
val oldArticles = breakingNewsResponse?.articles
val newArticles = resultResponse.articles
oldArticles?.addAll(newArticles)
}
return Resource.Success(breakingNewsResponse ?: resultResponse)
}
}
return Resource.Error(response.message())
}
fun searchNews(searchQuery: String) {
viewModelScope.launch {
searchNews.postValue(Resource.Loading())
val response = newsRepository.searchNews(searchQuery, searchNewsPage)
searchNews.postValue((handleSearchNewsResponse(response)))
}
}
fun handleSearchNewsResponse(response: Response<NewsResponse>): Resource<NewsResponse> {
if (response.isSuccessful) {
response.body()?.let { resultResponse ->
searchNewsPage++
if (searchNewsResponse == null) {
searchNewsResponse = resultResponse
} else {
val oldArticles = searchNewsResponse?.articles
val newArticles = resultResponse.articles
oldArticles?.addAll(newArticles)
}
return Resource.Success(searchNewsResponse ?: resultResponse)
}
}
return Resource.Error(response.message())
}
}
When i click on the icon on the toolbar menu the dialog appears and works fine but i can't seem to find a way to have the recycler view update with new data using given value for country
I searched everywhere and couldn't find a solution (or probably didn't understand it :S) can someone guide me into the right direction? I'm so lost...
When I click on the icon on the toolbar menu the dialog appears and works fine but I can't seem to find a way to have the recycler view update with new data using given value for country.
I am using RecyclerView to display a dynamic list of data and after I call an api I need to update my RecyclerView UI but the items in my RecyclerView does not change...
Below is my how I init my RecyclerView in my Fragment:-
forwardedList.layoutManager = LinearLayoutManager(context!!, RecyclerView.VERTICAL, false)
adapter = ForwardListAdapter(SmsHelper.getForwardedSms(context!!))
forwardedList.adapter = adapter
Below is my custom RecyclerView Adapter:-
class ForwardListAdapter(val forwardedList: List<SmsData>) : RecyclerView.Adapter<ForwardListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ForwardListAdapter.ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.forwarded_item, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ForwardListAdapter.ViewHolder, position: Int) {
holder.bindItems(forwardedList[position])
}
override fun getItemCount(): Int {
return forwardedList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(sms: SmsData) {
val simSlotText: TextView = itemView.findViewById(R.id.simSlot)
val senderText: TextView = itemView.findViewById(R.id.sender)
simSlotText.text = "[SIM ${sms.simSlot}] "
senderText.text = sms.sender
}
}
}
I am currently updating my RecyclerView from SmsHelper class as below:-
val fragments = mainActivity!!.supportFragmentManager.fragments
for (f in fragments) {
if (f.isVisible) {
if (f.javaClass.simpleName.equals("ForwardedFragment")) {
val fg = f as ForwardedFragment
fg.adapter.notifyDataSetChanged() <----- HERE
} else if (f.javaClass.simpleName.equals("FailedFragment")) {
val fg = f as FailedFragment
fg.adapter.notifyDataSetChanged()
}
}
}
As I observed, you did not really change the adapter's data but only called notifyDataSetChanged. You cannot just expect the data to be changed automatically like that since notifyDataSetChanged only:
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
You need to change the data by yourself first, then call notifyDataSetChanged.
class ForwardListAdapter(private val forwardedList: MutableList<SmsData>) : RecyclerView.Adapter<ForwardListAdapter.ViewHolder>() {
// ...
fun setData(data: List<SmsData>) {
forwardedList.run {
clear()
addAll(data)
}
}
// ...
}
Then do it like this:
adapter.run {
setData(...) // Set the new data
notifyDataSetChanged(); // notify changed
}
I'm making an app in android using Kotlin, Material Design Components and the new architecture components.
I have an activity that starts a DialogFragment onCreate
The fragment has 6 Views that, via an observer, observe a different LiveDate for each and every one.
While checking all the this setup work I noticed that after 7 view switching I get
2020-05-12 20:43:19.346 4778-4778/package E/InputEventReceiver: Exception dispatching input event.
2020-05-12 20:43:19.346 4778-4778/package E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
2020-05-12 20:43:19.357 4778-4778/package E/MessageQueue-JNI:
java.lang.ArrayIndexOutOfBoundsException: length=9; index=9
at android.text.Layout$HorizontalMeasurementProvider.get(Layout.java:1589)
...
I cheked the following things:
did all the setup on only one view -> still crashes
did all the setup on only one view but without using the "createDateFieldObserver" method -> still carshes
not calling the observer -> no crash
calling the observer but without the LocalDate.format -> no crash
I concluded the probleme is in the format function but I do not understand why.
The error is not pointing in that direction.
Any ideas?
Activity code
class UITestingActivity: FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_greenhouse)
val dialog = LabTimesDialogFragment()
dialog.show(supportFragmentManager, "LabTimes")
}
}
Fragment Code
class TimesDialogFragment : DialogFragment() {
companion object Companion {
private val TAG: String = "TimesDialog"
}
private val datesViewModel: TimesViewModel by activityViewModels()
private lateinit var datesViews: Map<LiveData<LocalDate>, TextInputEditText>
override fun onCreateDialog(savedInstanceState: Bundle?) : Dialog {
val viewsArray: Array<TextInputEditText>
return activity?.let {
val builder = AlertDialog.Builder(it)
val inflater = requireActivity().layoutInflater
val rootView: View = inflater.inflate(R.layout.dialog_filter_times, null)
builder.setView(rootView)
.setPositiveButton(R.string.feed) { dialog, id -> closeDialog() }
.setNegativeButton(R.string.cancel) { dialog, id -> getDialog()?.cancel() }
val dialog: AlertDialog = builder.create()
val fromSampling: TextInputEditText = rootView.findViewById(R.id.from_sampling) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
val toSampling: TextInputEditText = rootView.findViewById(R.id.to_sampling) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
val fromSending: TextInputEditText = rootView.findViewById(R.id.from_sending) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
val toSending: TextInputEditText = rootView.findViewById(R.id.to_sending) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
val fromReceiving: TextInputEditText = rootView.findViewById(R.id.from_receiving) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
val toReceiving: TextInputEditText = rootView.findViewById(R.id.to_receiving) ?: throw IllegalStateException("Missing date view in LabTimesFilterDialog")
datesViews = mapOf(datesViewModel.fromSampling to fromSampling,
datesViewModel.toSampling to toSampling,
datesViewModel.fromSending to fromSending,
datesViewModel.toSending to toSending,
datesViewModel.fromReceiving to fromReceiving,
datesViewModel.toReceiving to toReceiving
)
for ((liveData, textView) in datesViews) {
liveData.observe(this, createDateFieldObserver(textView))
textView.setOnClickListener { v ->
Log.d(TAG, "hello"+v.id)
}
}
return dialog
} ?: throw IllegalStateException("Activity cannot be null")
}
private fun closeDialog() {
// save dates to ViewModel
// closeDialog
TODO()
}
private fun createDateFieldObserver(tw: TextInputEditText): Observer<LocalDate> {
return Observer { date ->
Log.d(TAG, "obs"+tw.id)
tw.setText(date.format(DateTimeFormatter.ISO_DATE))
//tw.setText("hello")
}
}
}
ViewModel
class TimesViewModel : ViewModel() {
val fromSampling: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
val toSampling: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
val fromSending: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
val toSending: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
val fromReceiving: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
val toReceiving: MutableLiveData<LocalDate> = MutableLiveData(LocalDate.now())
}
it has been a while since I programmed for android. Everything I'm using here is new to me so if you spot an anti-pattern in this little code I would be glad to know.
Tnx
Turns out it was because of the layout.
There was no enough room in the view to display the whole date.
I don't understand why it causes indexoutofbound but the solution is to simply make the view "wrap_content" or bigger
I an trying to do a simple app, in which I use RecyclerView.
Here are my files.
MainActivity.kt
activity_main.xml --> which has RecyclerView (recylerViewMain)
single_row.xml --> single row for recyclerViewMain
MainAdapter.kt --> where all bindings , ViewHolder and inflating
I have also
Product.kt --> model for Products
Now, here what i am trying to do.
I have added Plus and Minus buttons on the side of itemUnit and whenever i click those items it does the job i wanted, increasing the itemUnit and eventually, itemAmount
However, this happens only on Row, and it doesn't change the Sub Total (TextView) in main_activity.xml file.
Is there a way to change the main_activity textView whenever textView in the Row of Recyclerview changes (or whenever button clicked on the row) ?
I am editing the code here.
Sub Total amount doesn't change until I click an item button (Granola, Brownie etc.). Only after I click the these items Sub Total changes and gives the updated amount.
the interface solution didnt work for me, I think I couldnt implement it right.
here are the codes ;
class MainActivity : AppCompatActivity(), ItemChangeListener {
override var subTotalAmnt: Double = 30.0
//override var subTotalAmount: Double = 50.0
//override fun onItemPriceChange(20.0)
lateinit var mRecyclerView : RecyclerView
private lateinit var sDatabase: DatabaseReference
var trId: Long = 0
var discAmnt : Double = 0.00
var unt = 1
var tr :Trans ?= null
var sb = 0.00
var disc = sb*.1
var tt = sb-disc
var list = ArrayList<Product>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
//var subto = findViewById(R.id.txtSubAmount) as TextView
onItemPriceChange(20.0)
txtSubAmount.text = subTotalAmnt.toString()
sDatabase = FirebaseDatabase.getInstance().getReference().child("Sales")
sDatabase.child("Sales").addValueEventListener(object:ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
}
override fun onDataChange(p0: DataSnapshot) {
if(p0.exists()) {
trId = p0.childrenCount
println(trId)
}
}
})
mRecyclerView = findViewById(R.id.recyclerView_main)
mRecyclerView.layoutManager = LinearLayoutManager(this)
mRecyclerView.adapter = MainAdapter(this, list)
and my Adapter Class;
class MainAdapter(val context: Context, val items : List<Product>) : RecyclerView.Adapter<MainAdapter.PartViewHolder>() {
override fun onBindViewHolder(p0: MainAdapter.PartViewHolder, p1: Int) {
p0.bindItems(items[p1])
}
var itemListener: ItemChangeListener? = null
fun setListener(listener: ItemChangeListener) {
this.itemListener = listener
}
override fun getItemId(position: Int): Long {
return super.getItemId(position)
}
override fun getItemCount(): Int {
return items.size
}
// Inflates the item views
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PartViewHolder {
// LayoutInflater: takes ID from layout defined in XML.
// Instantiates the layout XML into corresponding View objects.
// Use context from main app -> also supplies theme layout values!
val inflater = LayoutInflater.from(parent.context)
// Inflate XML. Last parameter: don't immediately attach new view to the parent view group
val view = inflater.inflate(R.layout.sinlge_row, parent, false)
return PartViewHolder(view)
}
// Binds each product in the ArrayList to a view
inner class PartViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
// Holds the TextView that will add each product to
fun bindItems(prd: Product) {
val textViewName = itemView.txtOrderNumber
var textViewUnit = itemView.txtItemUnit
val textViewPrice = itemView.txtItemPrice
val textViewAmount = itemView.txtItemAmount
var id = adapterPosition
var unitN: Int = 1
textViewName.text = prd.pName
textViewUnit.text = prd.pUnit.toString()
textViewPrice.text = prd.pPrice.toString()
var itemPrice = prd.pPrice
var itemAmount = itemPrice.times(unitN)
textViewAmount.text = itemAmount.toString()
itemView.btnPlus.setOnClickListener {
println("item id : " + id)
//itemListener = ItemChangeListener
itemListener?.onItemPriceChange(10.0)
// increase the Product model single unit
prd.pUnit = unitN++
// println("Here is the " +MainActivity().list.get(id))
// bind txtItemUnit from single_row to changed unitN (single unit)
textViewUnit.text = unitN.toString()
// change the Product model single pAmount
prd.pAmount = prd.pPrice.times(unitN)
// bind txtItemAmount from single_row to Product pAmount
textViewAmount.text = prd.pAmount.toString()
//txtSubAmount.txt =
//MainActivity().doSomething(subTotalAmount)
}
itemView.btnMinus.setOnClickListener(View.OnClickListener {
if (unitN >= 1) {
prd.pUnit = unitN--
println(prd.pUnit)
textViewUnit.text = unitN.toString()
textViewAmount.text = prd.pPrice.times(unitN).toString()
} else
prd.pUnit = 1
textViewUnit.text = prd.pUnit.toString()
textViewAmount.text = prd.pPrice.times(prd.pUnit).toString()
})
}
}
}
and, Interface
interface ItemChangeListener {
var subTotalAmnt : Double
fun onItemPriceChange(subTotalAmount : Double){
this.subTotalAmnt = subTotalAmount
println("onItemPriceChange "+subTotalAmnt)
}
}
I am sorry for this terrible explanation as I am not native, but willing to explain more for help.
Kind Regards.
Edited MainAdapter
class MainAdapter(val context: Context, val items : List<Product>) : RecyclerView.Adapter<MainAdapter.PartViewHolder>() {
override fun onBindViewHolder(p0: MainAdapter.PartViewHolder, p1: Int) {
p0.bindItems(items[p1])
}
lateinit var itemListener: ItemChangeListener
fun setListener(listener: ItemChangeListener) {
this.itemListener = listener
}
override fun getItemId(position: Int): Long {
return super.getItemId(position)
}
override fun getItemCount(): Int {
return items.size
}
// Inflates the item views
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PartViewHolder {
// LayoutInflater: takes ID from layout defined in XML.
// Instantiates the layout XML into corresponding View objects.
// Use context from main app -> also supplies theme layout values!
val inflater = LayoutInflater.from(parent.context)
// Inflate XML. Last parameter: don't immediately attach new view to the parent view group
val view = inflater.inflate(R.layout.sinlge_row, parent, false)
return PartViewHolder(view)
}
// Binds each product in the ArrayList to a view
inner class PartViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
// Holds the TextView that will add each product to
fun bindItems(prd: Product) {
val textViewName = itemView.txtOrderNumber
var textViewUnit = itemView.txtItemUnit
val textViewPrice = itemView.txtItemPrice
val textViewAmount = itemView.txtItemAmount
var id = adapterPosition
var unitN: Int = 1
textViewName.text = prd.pName
textViewUnit.text = prd.pUnit.toString()
textViewPrice.text = prd.pPrice.toString()
var itemPrice = prd.pPrice
var itemAmount = itemPrice.times(unitN)
textViewAmount.text = itemAmount.toString()
itemView.btnPlus.setOnClickListener {
println("item id : " + id)
//itemListener = ItemChangeListener
itemListener.onItemPriceChange(20.0)
// increase the Product model single unit
prd.pUnit = unitN++
// println("Here is the " +MainActivity().list.get(id))
// bind txtItemUnit from single_row to changed unitN (single unit)
textViewUnit.text = unitN.toString()
// change the Product model single pAmount
prd.pAmount = prd.pPrice.times(unitN)
// bind txtItemAmount from single_row to Product pAmount
textViewAmount.text = prd.pAmount.toString()
//txtSubAmount.txt =
//MainActivity().doSomething(subTotalAmount)
}
itemView.btnMinus.setOnClickListener(View.OnClickListener {
if (unitN >= 1) {
prd.pUnit = unitN--
println(prd.pUnit)
textViewUnit.text = unitN.toString()
textViewAmount.text = prd.pPrice.times(unitN).toString()
} else
prd.pUnit = 1
textViewUnit.text = prd.pUnit.toString()
textViewAmount.text = prd.pPrice.times(prd.pUnit).toString()
})
}
}
}
I think you can do it using interface.
First you create interface definition (in a separate file or in adapter).
-- for eg: interface ItemChangeListener { fun onItemPriceChange(pass itemprice or totalprice) }
next you create an object of listener inside adapter
Like lateinit var listener: ItemChangeListener inside adapter (set using fun setListener(listener:ItemChangeListener){ // code } ).
Let the main activity implement the interface.
pass the mainActivity this to the adapter.setListener
on Clicking the button, you can call listener.onItemPriceChange(pass itemprice or totalprice)
you can get the parameter on main activity in this way.
Check this link for some details.. Same can be done using constructor parameter I guess.