Passing a variable's value not reference in an OnClickListener()

I'm trying to set up a large number OnClickListeners through a for loop. Each view should run a method when clicked; view 0 should run the method with the value 0, view 1 with the value 1, etc.

However, if I declare the OnClickListener using a variable which increments through the for loops, the OnClickListener remembers the reference to the variable rather than the value of the variable at the time it was declared.

That's probably not very clear — here's the code:

for (int i = 0; i < 20; i++) {
    cells[i] = (ImageView) findViewById(cellIDs[i]);
    cells[cellnumber++].setOnClickListener(new OnClickListener() {
    public void onClick(View v){
          cellClicked(cellnumber, v);

That correctly sets up the OnClickListeners for each cell, but whichever one is clicked, it always runs calls cellClicked with value of 21.

I know I can manually set up the OnClickListeners using cell[0] . . . cellClicked(0, v), but is there a way to do it so that the ClickListener is passed the value of the variable rather than a reference to the variable in the for loop?

(I saw a few pages which said that Java normally operates with passing values and not references, but I assume the Android libraries somehow do it differently and hence my difficulties here.)

Asked by: Owen867 | Posted: 24-01-2022

Answer 1

There's nothing "special" about the Java semantics in Android.

cellClicked isn't actually called when you create each listener, and cellnumber isn't local to the anonymous class you're creating each time, so each listener is referring to the same variable and thus gets the same value.

Use the View.setTag() method to attach the cell ID to each View. Then you only need one instance of the listener which, in its onClick method, calls v.getTag() to get the cell ID.

Here's some wholly untested code. I don't actually know off the top of my head if you can cast a boxed Integer like that. Anyway, it's a start:

OnClickListener listener = new OnClickListener() {
    public void onClick(View v) {
        int cellId = (int) v.getTag();
        cellClicked(cellId, v);

View v;
for (int i = 0; i < 20; i++) {
    v = findViewById(cellIDs[i]);

Answered by: Daniel185 | Posted: 25-02-2022

Answer 2

Your OnClickListener is not storing any state, so you are always getting the same value of cellnumber. You probably want to create a custom OnClickListener extension that takes a cellnumber via the constructor and stores it as a member variable for later, this way each listener will have a different copy of the cellnumber value rather than all referencing the same one.

Answered by: Charlie175 | Posted: 25-02-2022

Similar questions

OnClickListener() implementation of Array Of Buttons in Android

I am writing an Android Application which outputs some array of buttons dynamically. My question is how to implement onClickListener() functionality for Array Of Buttons. I mean how to recognize the button that is clicked in public void onClick() method ? I need to display a toast based on the button that is clicked.

java - what is the parameter passing to the OnClickListener()?

I'm new to java with C family background. I'm unable to dissect this code. If only you could help me by identifying what are the inner classes and interfaces in this block: startButton.setOnClickListener(new View.OnClickListener(){         public void onClick(View view)         {                                               usrnameobj = (EditText)findViewById(

listener - Android: The method OnClickListener() is undefined for the type View

I'm getting an error: The method OnClickListener() is undefined for the type View I'm new to android dev. These are my code: package com.example.playword; import; import; import; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; imp...

layout - Can I assign a "default" OnClickListener() for an Android Activity?

I have an Activity that, for each widget in the layout, I call setOnClickListener() to assign my OnClick() handler. In my OnClick() handler I use a switch statement to execute the desired code for each button based on the View parameter's ID. Is there a way to assign a default handler to the main view instead of having to make individual listener assignment calls for each widget in the view? =====================...

android - How to set onClickListener() for view of Spinner?

I want to catch user interaction with a spinner like onCLickListener. Do to the 'don't call onClickListener() on AdapterView' error I found recommendations that you should override a constructer with a custom spinner to set onClickListener() on the view the spinner creates. Tried that: public class MySpinner extends Spinner { public static final String TAG = "MyApp"; public MySpinner(Context conte...

android - Given a listview with many data fields per row, how to separate only one field (id) from the row with onClickListener()

Given a listview with many data fields per row, how can we separate only one field (say an id) from the row withonClickListener() public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int position, long arg3) { Object dataRow = listView.getItemAtPosition(position); Log.e("hi, this is the full row of data, i just want 1 of the fields", dataR...

java - Way of setting of onClickListener()

I created a ImageView object(img) and pass some resources through the same object(img) to a Linear Layout with a for-loop. On each Iteration of the loop I invoke a setOnClickListener() on img(img.setOnClickListener()) to show a Toast that reflects the value of the loop controller variable (i). The code segment i tried is below: for (i = 1; i &lt;= 6; i++) ...

android - OnClickListener() must override a superclass method?

With this code: import; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; . . . Button buttonAuthorizeUsers = (Button) findViewById(; buttonAuthorizeUsers.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) {...

java - ImageView onClickListener()

I am having trouble with changing the state of ImageView which marks list items as bookmarked. People have mentioned to create a new OnClickListener() which I have but when I click on the ImageView it does go to the focused state but when you finish clicking it does not change to the pressed state image. Furthermore, when I click on the list item I notice that the ImageView is...

android - compiler complains on onClickListener()

I am just starting on android programming. While trying out something the compiler is complaining on this: Button button1main = (Button) findViewById(; button1main.setOnClickListener(new onClickListener() { public void onClick(View v) { //Blah }); The compiler complains The method setOnClickListener(View.OnClickListener) in the type View is not...

Still can't find your answer? Check out these communities...

Android Google Support | Android Community | Android Community (Facebook) | Android