oldmanB
oldmanB

Reputation: 1

Android - Creating Multiple onClickListeners in a for loop (Kotlin)

I'm trying to instantiate a large number (~600) onclick listeners for a large grid of buttons. I've created a function that stores the id's of each square in a list called squareList, in which each square is assigned a string value id (sq000, sq001, sq002)

I'd like to create a for loop that pulls the id of each square and then creates an onClicklistener, sort of like:

fun createSquareListeners(listOfSquares: MutableList<String>)
{
    for(square in listOfSquares)
    {
       square.setOnClickListener{ //Do Something}
    }
}

The other way I thought of implementing this was to write a single onClick function, and attach it to each button in the xml file, but I'm not really sure what's possible as I'm quite new to Kotlin/Java

Upvotes: 0

Views: 2232

Answers (6)

kelalaka
kelalaka

Reputation: 5636

You can listen onClick on your activity

class MyActivity:Activity(), OnClickListener {
  fun onClick(v:View) {
    R.id.Button1
    run({
      //...
      break })
    R.id.Button2
    run({
      //..
      break })
  }
}

If you plan to change some behavior according to ID's, you don't need the case here. Extend the Button class as GridButton and make sure that the class type is GridButton by

if (obj is C)
{
  //your code
}

Upvotes: -2

Kaveri
Kaveri

Reputation: 1088

One of the direct method to achieve this would be by creating one funtion to be called on click event for all the buttons and inside the function you can identify the button pressed by getting its id and using a when operator to perform different operations in different button clicks.

inside the layout add the add Button like this:-

<LinearLayout 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"
tools:context=".MainActivity">

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:onClick="toastMe"
    tools:layout_editor_absoluteX="95dp"
    tools:layout_editor_absoluteY="216dp" />
<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:onClick="toastMe"
    tools:layout_editor_absoluteX="95dp"
    tools:layout_editor_absoluteY="216dp" />

  </LinearLayout>

and inside you kotlin code , put your function like the following:-

 fun toastMe(view : View) {
   when (view.id) {
       R.id.button -> print("x == 1")
       R.id.button2 -> print("x == 2")
       else -> { // Note the block
           print("x is neither 1 nor 2")
       }
   }

when replaces the switch operator of java language.

Upvotes: 0

Brent
Brent

Reputation: 778

why not just set an on item listener on the entire grid layout and then have a listener for inside of that like

gridView.setOnItemClickListener(object:OnItemClickListener() {
   fun onItemClick(parent:AdapterView<*>, v:View,
              position:Int, id:Long) {
      // DO something
   }
})

this way you wouldn't need to have the id's of everything inside the grid view then you could just change where you going basted on the position:Int clicked inside of the grid view or am i not understanding what your trying to do?

Upvotes: 2

Prithvi Bhola
Prithvi Bhola

Reputation: 3151

If each button needs to have the same functionality in its setOnClickListener, then this is what you can do.

listOf(listOfSquares).forEach {
            it?.setOnClickListener {
               // Do something
        }
}

Upvotes: 0

C0D3LIC1OU5
C0D3LIC1OU5

Reputation: 8680

You do not need a new ClickListener object for every button. Just make ONE click listener instance (have your activity implement it or make a new class for it or use an anonymous class). You can pass that instance into your button's setOnClickListener method. You can tell which button was clicked by using view.getId() method and comparing it against your button id's.

Upvotes: 1

Nelson Almendra
Nelson Almendra

Reputation: 881

I'm not sure if I understood right but you can try to encapsulate the id and the listener in a Square object.

Something like this:

class Square(context: Context?, id: String) : Button(context) {

    override fun setOnClickListener(l: OnClickListener?) {
        super.setOnClickListener(l)
        //TODO: use your id to something
    }
}

You will have to change your listOfSquares to be a MutableList<Square>.

Upvotes: 0

Related Questions