I'm trying to pass the clicked element to the calling activity in my RecyclerView in the onBindViewHolder method. There I need the just clicked element or the number. How do I do it?
class AddNewHomeFragment : Fragment() {
rv_img.layoutManager = GridLayoutManager(requireContext(),3)
adapter = CustomerAdapter(requireContext(),listImg){
//NEED CLICKED ITEM NUMBER HERE
var intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent,IMAGE_REQUEST)
}
... }
Adapter Class (CustomerAdapter):
class CustomerAdapter(val context: Context,
private val listImg:ArrayList<Bitmap>, private val onClickFunction: ((Any?) -> Unit)? = null):RecyclerView.Adapter<CustomerAdapter.MyCustomViewHolder>() {
...
override fun onBindViewHolder(holder: MyCustomViewHolder, position: Int) {
holder.customImg.setImageBitmap(listImg[position])
holder.customImg.setOnClickListener {
this#CustomerAdapter.onClickFunction?.invoke(listImg[position])
}
}
}
Your constructor should be:
class CustomerAdapter(val context: Context,
private val listImg:ArrayList<Bitmap>,
private val onClickFunction: ((Int) -> Unit)? = null
):RecyclerView.Adapter<CustomerAdapter.MyCustomViewHolder>()
Your function takes an integer position, not an Any, and it can't be null.
Your usage of it should go
adapter = CustomerAdapter(requireContext(),listImg){ position->
var intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent,IMAGE_REQUEST)
}
Then you can use position within the function.
Related
Trying to get a button to open another activity in android studio using kotlin. I am user a recycles view to do so. I have view card and want to edit the data in the card so I am user onClick to get the page to respond but that does seem to work I tried researching it but nothing come up that I can make sense of. Here is the code.
Thank you for all your help I appreciate it
This is the adapter class:
```class EventAdapter(var mListener: onItemClickListener, var context: Context, val items: ArrayList<EventModelk>):
RecyclerView.Adapter<EventAdapter.ViewHolder>() {
interface onItemClickListener {
fun onItemClick(position: Int)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemview = LayoutInflater.from(context).inflate(
R.layout.eventitems,
parent,
false,
)
return ViewHolder(itemview, mListener)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
holder.setEmail.text = item.eEmail
holder.setNotes.text = item.nNotes
holder.setData.text = item.dDate
holder.setTime.text = item.tTime
if (item.repeat == 1) {
holder.setReap.isChecked = true
// holder.setReap.text = item.repeat.toString()
}
if (position % 2 == 0) {
holder.main.setBackgroundColor(
ContextCompat.getColor(
context,
R.color.colorLightGray
)
)
} else {
holder.main.setBackgroundColor(ContextCompat.getColor(context, R.color.colorWhite))
}
holder.pushimg.setOnClickListener {
if (context is UpdateDataInfo) {
(context as UpdateDataInfo).updateEvent(item)
}
}
// interface onItemClickListener{
// fun onItemClick(position: Int)
}
override fun getItemCount(): Int {
return items.size
}
class ViewHolder(view: View,onItemClickListener: onItemClickListener): RecyclerView.ViewHolder(view),onItemClickListener {
val main: CardView = view.IIMain
val setData: TextView = view.set_date
val setTime: TextView = view.set_time
val setEmail: TextView = view.Tv_email
val setNotes: TextView = view.set_note
val setReap: CheckBox =view.is_repeat
val pushimg: ImageView = view.img_edit
val onItemClickListener = onItemClickListener
override fun onItemClick(position: Int) {
onItemClickListener.onItemClick(absoluteAdapterPosition)
}
}
}```
This is my code for getting the click to go to another activity:
class CurrentSch : AppCompatActivity(), EventAdapter.onItemClickListener {
//private var change =imageView2?.isClickable
var STORAGE_LOCAL =true
val eventlist = ArrayList<EventModelk>()
#RequiresApi(Build.VERSION_CODES.N)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.currentsch)
btnNewApp2.setOnClickListener {
val intent = Intent(this, NewPlan::class.java)
startActivity(intent)
}
seeAllEventInPlan()
}
//private var change =imageView2?.isClickable
private fun getEventist(): ArrayList<EventModelk>{
val eventdatabase = EventDatabasek(this)
return eventdatabase.veiwEvent()
}
fun seeAllEventInPlan() = if(getEventist().size >0){
ryc_eventLists.visibility = View.VISIBLE
viewnotview.visibility = View.GONE
ryc_eventLists.layoutManager = LinearLayoutManager(this)
val eventAdapter = EventAdapter(this,this, getEventist())
ryc_eventLists.adapter = eventAdapter
}else{
ryc_eventLists.visibility = View.GONE
viewnotview.visibility = View.VISIBLE
}
override fun onItemClick(position: Int) {
val item = eventlist[position]
img_edit.setOnClickListener {
val intent = Intent(this, UpdateDataInfo::class.java)
intent.putExtra("Events", position)
startActivity(intent)
}
}
}
Inside the onBindViewHolder function, simply call mListener.onItemClick(position) for example if you wanted to open another Activity on click of setData, then you can write below code in onBindViewHolder
holder.setData.setOnClickListener { mListener.onItemClick(position) }
according to your above code , you have made callbacks where you calling thee adapter you will get callback there and you will open a activity there .. .. but you can simple open your new activity from adapter like this ..
holder.itemView.setOnClickListener(View.OnClickListener {
val intent = Intent (context,SomeActivity::class.java)
context.startactivity(intent)
})
I marked the parts that were added (added to code) after the moment
when the application was working, the data was successfully downloaded
from the database. I may be mistakenly trying to pass this information
to another screen. I tried to find a video that connects to the
database and forwards that data of recicler on another screen, but
without success, or they are in Java, which I understand less.
MySecondActivity
class BookDescription : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_book_description)
var books = intent.getSerializableExtra("noti") as Book //added to code
Glide.with(this).load(books.imageUrl).into(bookImg2)// added to code
nameTxt2.text = books.name //added to code
autorTxt2.text = books.writer //added to code
}
}
MainActivity
class MainActivity : AppCompatActivity() {
private lateinit var adapter : Adapter
private val viewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java)}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setUpRecyclerView()
}
private fun setUpRecyclerView(){
adapter = Adapter(this){
startBookDescription()
}
recycle.layoutManager = GridLayoutManager(this, 2)
recycle.adapter = adapter
observerData()
}
fun observerData(){
viewModel.fetchUserData().observe(this,Observer{
adapter.setListdata(it)
adapter.notifyDataSetChanged()
})
}
private fun startBookDescription(){
val intent = Intent (this, BookDescription::class.java )
startActivity(intent)
}
}
Class Adapter with inner class Holder
class Adapter(private val context: Context,
private val onItemCliked: () -> Unit ) : RecyclerView.Adapter<Adapter.Holder>() {
private var datalist = mutableListOf<Book>()
fun setListdata(data: MutableList<Book>){
datalist = data
}
inner class Holder(itemView : View) : RecyclerView.ViewHolder(itemView){
fun bindView(book: Book, onItemClicked: () -> Unit){
Glide.with(context).load(book.imageUrl).into(itemView.bookImg)
itemView.nameTxt.text = book.name
itemView.autorTxt.text= book.writer
itemView.setOnClickListener { onItemClicked.invoke() }
itemView.bookImg.setOnClickListener(View.OnClickListener { //added
val intent = Intent(context, BookDescription::class.java)//added to code
intent.putExtra("noti", book)//added to code
context.startActivity(intent)//added to code
})
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(context).inflate(R.layout.book_format, parent,
false )
return Holder(view)
}
override fun onBindViewHolder(holder: Holder, position: Int) {
val book = datalist[position]
holder.bindView(book, onItemCliked)
}
override fun getItemCount(): Int {
return if (datalist.size> 0){
datalist.size
}else{
0
}
}
}
The problem is here:
intent.putExtra("noti", book)
The book variable is of type Book, which is apparently neither a Parcelable or Serializable class. You must implement one of these two interfaces in the Book class in order to add it to an Intent or Bundle.
Assuming Book is made up of simple data types (String, Int, etc), then you can use the #Parcelize annotation to easily implement Parcelable. More here: https://developer.android.com/kotlin/parcelize
In your bindView() method, you have this block of code:
val intent = Intent(context, BookDescription::class.java)//added to code
intent.putExtra("noti", book)//added to code
context.startActivity(intent)//added to code
})
However, you don't actually do anything with this Intent; you start your activity from another place:
private fun startBookDescription(){
val intent = Intent (this, BookDescription::class.java )
startActivity(intent)
}
You will have to pass the Book instance to this method (via invoke(book)). This will require a corresponding type change to the click listener parameter of your adapter.
This Line is wrong adapter = ItemAdapter(applicationContext,userViewModel.getListUsers())
**Because the adapter parameters context: Context, arrayList: ArrayList (but not MutableLiveData) **
I don’t know what to do about it, and I’m not entirely sure if I am using the LiveData correctly.
My Adapter
class ItemAdapter(var context: Context, private var arrayList: ArrayList<NumberModel>):RecyclerView.Adapter<ItemAdapter.ItemHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder{
val itemHolder = LayoutInflater.from(parent.context).inflate(
R.layout.grid_layout_list_item,
parent,
false
)
return ItemHolder(itemHolder)
}
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
var positionOfNumber:NumberModel = arrayList.get(position)
holder.textOfNumber.text = positionOfNumber.numberOfElement
holder.button.setOnClickListener {
var positionForDelete = holder.adapterPosition
arrayList.removeAt(positionForDelete)
notifyItemRemoved(positionForDelete)
notifyItemRangeChanged(positionForDelete,arrayList.size)
}
}
override fun getItemCount(): Int {
return arrayList.size
}
class ItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var textOfNumber = itemView.findViewById<TextView>(R.id.numberTextView)
var button:Button = itemView.findViewById(R.id.buttonClick)
}
}
MainActivity
recyclerView = findViewById(R.id.recyclerViewList)
gridLayoutManager = GridLayoutManager(applicationContext,2,LinearLayoutManager.VERTICAL,false)
recyclerView?.layoutManager = gridLayoutManager
recyclerView?.setHasFixedSize(true)
recyclerView?.adapter = adapter
userViewModel.getListUsers().observe(this, Observer {
it?.let {
adapter = ItemAdapter(applicationContext,userViewModel.getListUsers())
}
})
}
ViewModel
class MainActivityViewModel : ViewModel() {
var elementsList: MutableLiveData<ArrayList<NumberModel>> = MutableLiveData()
init {
elementsList.value = setElements()
}
fun getListUsers() = elementsList
private fun setElements() : ArrayList<NumberModel> {
var itemArrayList:ArrayList<NumberModel> = ArrayList()
itemArrayList.add(NumberModel("1"))
itemArrayList.add(NumberModel("2"))
itemArrayList.add(NumberModel("3"))
itemArrayList.add(NumberModel("4"))
itemArrayList.add(NumberModel("5"))
itemArrayList.add(NumberModel("6"))
itemArrayList.add(NumberModel("7"))
itemArrayList.add(NumberModel("8"))
itemArrayList.add(NumberModel("9"))
itemArrayList.add(NumberModel("10"))
return itemArrayList
}
Reason for Because the adapter parameters context: Context, arrayList: ArrayList (but not MutableLiveData) this error.
we are passing the MutableLiveData instead of ArrayList. so we need to pass the ArrayList as the second parameter.
userViewModel.getListUsers().observe(this, Observer {
it?.let { list->
adapter = ItemAdapter(applicationContext,list)
}
})
userViewModel.getListUsers() will give the ArrayList so we can pass this to get the instance of ItemAdapter
instead of passing the applicationContext we can give thisor requireActivity() (will give the MainActivity context),
if we pass the applicationContext, we may lead to a memory leak we have to pass the right context to the object.
I'm successfully passing data from MainActivity to my recyclerView via adapter, and my view with items is rendering correctly. However, I need to change one member of my item object on click (status), and i wrote a method for that (updateStatus), and it works great, it changes the value and save it to database.
But i cannot refresh my recyclerView, so it could render changed Status attribute. I need to go back on my phone, reenter, and then it renders it correctly. I have tried everything, from notifyDataSetChanged to restarting adapter, no luck. There is something missing and I can't find what.
Here is my MainActivity class
class MainActivity : AppCompatActivity() {
private var posiljkaDAO: PosiljkaDAO? = null
private var dostavnaKnjizicaDAO: DostavnaKnjizicaDAO? = null
private var allItems: ArrayList<DostavnaKnjizicaModel> = arrayListOf()
var adapter = RecycleViewAdapter(allItems)
private var eSifraPosiljke: EditText? = null
#RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_listview)
//get logo
supportActionBar!!.setDisplayShowHomeEnabled(true)
supportActionBar!!.setLogo(R.drawable.logo_bp)
supportActionBar!!.setDisplayUseLogoEnabled(true)
dostavnaKnjizicaDAO = DostavnaKnjizicaDAO(this)
dostavnaKnjizicaDAO?.closeDB()
getAllItems(this)
//connecting adapter and recyclerView
adapter = RecycleViewAdapter(allItems)
recycleView.adapter = adapter
recycleView.layoutManager = LinearLayoutManager(this)
recycleView.setHasFixedSize(true)
eSifraPosiljke = findViewById<EditText>(R.id.eSifraPosiljke)
posiljkaDAO = PosiljkaDAO(this)
}
//method that gets all items from database
private fun getAllItems(context: Context) {
var dostavenFromLOcal = dostavnaKnjizicaDAO?.getAllLocalDostavneKnjizice(context)
if (dostavenFromLOcal != null) {
allItems = dostavenFromLOcal
}
}
//method that changes status of an item
fun changeStatus(context: Context, IdDostavne: Int, statusDostavne: Int) {
dostavnaKnjizicaDAO = DostavnaKnjizicaDAO(context)
dostavnaKnjizicaDAO?.changeStatus(IdDostavne, statusDostavne)
getAllItems(context)
adapter.notifyDataSetChanged()
}
}
and my Adapter class
class RecycleViewAdapter(var dostavneKnjiziceBP: ArrayList<DostavnaKnjizicaModel>)
: RecyclerView.Adapter<RecycleViewAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view){
val nazivPrimaoca: TextView = view.txtNazivPrimaoca
val brojPosiljke: TextView = view.txtBrojPosiljke
val statusDostave: TextView = view.txtStatusDostave
val imgMore: ImageView = view.img_more
val context: Context = view.context
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutView = LayoutInflater.from(parent.context).inflate(R.layout.urucenje_posiljke_layout, parent, false)
return ViewHolder(layoutView)
}
override fun getItemCount() = dostavneKnjiziceBP.size
#RequiresApi(Build.VERSION_CODES.KITKAT)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
//New variable to get all modeliPosiljakaBP and their position
var dosKnjizica = dostavneKnjiziceBP[position]
val mainActivity = MainActivity()
//Sending data to layout for display in specific field
if (dosKnjizica.naziv_primaoca != null) {
holder.brojPosiljke.text = "${dosKnjizica.id_dostavna_knjizica}, "
holder.nazivPrimaoca.text = "${dosKnjizica.naziv_primaoca}"
if (dosKnjizica.naziv_primaoca!!.length > 25) {
holder.nazivPrimaoca.text = "${dosKnjizica.naziv_primaoca!!.subSequence(0, 25)}..."
}
} else {
holder.brojPosiljke.text = "${dosKnjizica.id_dostavna_knjizica}"
holder.nazivPrimaoca.text = ""
}
holder.statusDostave.text = "${dosKnjizica.status_dostave_naziv}"
when (dosKnjizica.status_dostave) {
StatusDostaveEnum.Neurucena.value -> {
holder.statusDostave.setTextColor(Color.RED)
}
StatusDostaveEnum.Uruceno.value, StatusDostaveEnum.ZaRejon.value, StatusDostaveEnum.Nadoslano.value, StatusDostaveEnum.Izgubljeno.value -> {
holder.statusDostave.setTextColor(Color.GREEN)
}
StatusDostaveEnum.Obavjesteno.value, StatusDostaveEnum.ZaNarednuDostavu.value -> {
holder.statusDostave.setTextColor(Color.BLUE)
}
StatusDostaveEnum.Retour.value -> {
holder.statusDostave.setTextColor(Color.parseColor("#dda0dd"))
}
}
//Calling menu menu_pregled_drugih_vrsta_posiljke to display menu options on click on three dots
holder.imgMore.setOnClickListener {
val popupMenu = PopupMenu(holder.context, it, Gravity.START)
popupMenu.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.uruci -> {
//calling new activity from second item in dropdown menu
holder.imgMore.context.startActivity(
Intent(holder.imgMore.context, MainActivityInfo::class.java).putExtra(
"Id", dosKnjizica.id_dostavna_knjizica.toString()
)
)
true
}
//here i am calling my changeStatus method from MainActivity
R.id.obavjesti -> {
mainActivity.changeStatus(holder.context, dosKnjizica.id_dostavna_knjizica!!, StatusDostaveEnum.Uruceno.value)
Toast.makeText(holder.context, "obavjesti", Toast.LENGTH_SHORT).show()
true
}
R.id.vrati -> {
Toast.makeText(holder.context, "vrati", Toast.LENGTH_SHORT).show()
true
}
else -> false
}
}
popupMenu.inflate(R.menu.menu_urucenje_posiljke)
popupMenu.show()
}
}
}
Your adapter doesn't have the updated data. Initially, you fetch all data from the database and create an adapter with it: adapter = RecycleViewAdapter(allItems). Afterwards, you are updating the database, calling getAllItems(Context) but you don't pass the data to the adapter.
Add the line adapter.dostavneKnjiziceBP = allItems to the changeStatus method like this:
//method that changes status of an item
fun changeStatus(context: Context, IdDostavne: Int, statusDostavne: Int) {
dostavnaKnjizicaDAO = DostavnaKnjizicaDAO(context)
dostavnaKnjizicaDAO?.changeStatus(IdDostavne, statusDostavne)
getAllItems(context)
adapter.dostavneKnjiziceBP = allItems
adapter.notifyDataSetChanged()
}
Save dostavneKnjiziceBP as a private var inside the adapter and create functions for assigning and updating that ArrayList from within the adapter, using notifyDataSetChanged() everytime a change is done.
class RecycleViewAdapter internal constructor(
context: Context
) : RecyclerView.Adapter<RecycleViewAdapter.ViewHolder>() {
private var items = ArrayList<DostavnaKnjizicaModel>()
// ...
internal fun setItems(items: ArrayList<DostavnaKnjizicaModel>) {
this.items = items
notifyDataSetChanged()
}
override fun getItemCount() = this.items.size
}
Also, try using adapter.notifyItemChanged(updateIndex); if you know the index of the updated item.
I am using recyclerview in kotlin and I am new to kotlin. I have used button.setOnClickListner method inside this. I want to call a method which is in my mainActivity. How should I do it
I want to call below method which is in mainActivity
fun sendOrder() {
Log.e("TAG", "SendOrder: " )
}
my adapter is below
class CustomAdapterJob(val jobList: ArrayList<JobData>): RecyclerView.Adapter<CustomAdapterJob.ViewHolder>(){
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
val jobData :JobData = jobList[position]
holder?.textViewId?.text = jobData.id
holder?.textViewArea?.text = jobData.area
holder?.textViewCarType?.text = jobData.carType
holder?.textViewCarName?.text = jobData.carName
holder?. textViewDutyHours?.text = jobData.dutyHours
holder?.textViewWeeklyOff?.text = jobData.weeklyOff
holder?.textViewDriverAge?.text = jobData.driverAge
holder?.textViewDriverExperience?.text = jobData.drivingExperience
holder?.textViewOutstationDays?.text = jobData.outstationDays
holder?.textViewDutyDetails?.text = jobData.dutyDetails
holder?.button?.text =jobData.submit
if(jobData.submit == "true"){
holder?.button?.setVisibility(View.GONE);
}
holder?.button?.setOnClickListener( View.OnClickListener (){
Log.d("TAG", "job list position : ${jobList[position].id}")
var id = jobList[position].id
val p = Pattern.compile("-?\\d+")
val m = p.matcher(id)
while (m.find()) {
System.out.println(m.group())
sendOrder()
}
});
//To change body of created functions use File | Settings | File Templates.
}
override fun getItemCount(): Int {
return jobList.size//To change body of created functions use File | Settings | File Templates.
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val v=LayoutInflater.from(parent?.context).inflate(R.layout.job_card,parent,false)
return ViewHolder(v)
//To change body of created functions use File | Settings | File Templates.
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
val textViewId = itemView.findViewById<TextView>(R.id.job_id)
val textViewArea = itemView.findViewById<TextView>(R.id.area)
val textViewCarType = itemView.findViewById<TextView>(R.id.car_type)
val textViewCarName = itemView.findViewById<TextView>(R.id.car_name)
val textViewDutyHours = itemView.findViewById<TextView>(R.id.duty_hours)
val textViewWeeklyOff = itemView.findViewById<TextView>(R.id.weekly_off)
val textViewDriverAge = itemView.findViewById<TextView>(R.id.driver_age)
val textViewDriverExperience = itemView.findViewById<TextView>(R.id.driving_experience)
val textViewOutstationDays = itemView.findViewById<TextView>(R.id.outstation_days)
val textViewDutyDetails = itemView.findViewById<TextView>(R.id.duty_details)
val button = itemView.findViewById<Button>(R.id.apply_job)
}}
now how i have to call sendOrder() method in kotline
Its better you create a listener and pass it to the adapter.
Interface
interface ActivityInteractor {
fun onInteraction(data: Any?)
}
Implement the interface in your activity
class MainActivity : Activity(), ActivityInteractor {
override fun onCreate(savedInstance : Bundle) {
CustomAdapterJob(jobList, this)
}
override fun onInteraction(data: Any?) {
// you can do any activity related tasks here
sendOrder()
}
}
Accept the listener in your adapter
class CustomAdapterJob(val jobList: ArrayList<JobData>, val activityInteractor: ActivityInteractor) : RecyclerView.Adapter<CustomAdapterJob.ViewHolder>() {
holder?.button?.setOnClickListener( View.OnClickListener () {
Log.d("TAG", "job list position : ${jobList[position].id}")
var id = jobList[position].id
val p = Pattern.compile("-?\\d+")
val m = p.matcher(id)
while (m.find()) {
System.out.println(m.group())
//sendOrder()
activityInteractor.onInteraction(jobList[position].id)
}
});
}
Instead of creating the new interface you can implement onClickListener in the activity and can pass it as a parameter to the adapter class. In the adapter, you can set this onClick listener to your button.
Use kotlin data binding concept to avoid those boilerplate codes like findViewById. please check this link
First you need to create a context:
private val context: Context
Then add this context, along with other variables you might have, to your adapter constructor:
class Adapter(..., context: Context)
Inside you while loop:
while (m.find()) {
System.out.println(m.group)
if (context is MainActivity)
{
(context as MainActivity).SendOrder()
}
}
Apologies for any syntax error, etc. My Kotlin is still a little rough.
The easiest solution would be to your activity as parameter to your recycler view. Then you could easaly call that function. But obviously this is not a very good aproach, so you should prefer the following.
Create an interface which is implemented by your activity and called instead of the activities method. Within the implementation of the interface function you can call the activity function or whatever you like. As it is implemented by the activity itself you have full access to the whole activity context.
A short example how this could be implemented is already answered here
you can do like this:
holder?.button?.setOnClickListener( View.OnClickListener (){
Log.d("TAG", "job list position : ${jobList[position].id}")
var id = jobList[position].id
val p = Pattern.compile("-?\\d+")
val m = p.matcher(id)
while (m.find()) {
System.out.println(m.group())
mySendOrder()
}
});
public void mySendOrder(){
}
and then in main activity:
yourCustomAdapter = new YourCustomAdapter(){
public void mySendOrder(){
sendOrder();
}
}
In case if you don't need Context or Activity object in your adapter. You can pass callback as parameters. May be something like this
class MyAdapter(private val sendOrder: () -> Unit = {}) : BaseAdapter() {
fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
sendOrder()
}
}
Then implement callback in Activity
fun onCreate(...) {
recyclerView.adapter = MyAdapter() {
// Do something
}
}