onClickListener as Array (or pass variables to Listener)?

Put your problem here if it does not fit any of the other categories.

onClickListener as Array (or pass variables to Listener)?

Postby thekooliest » Thu Apr 07, 2011 10:31 pm

I am using an onClickListener for my Layout. I have many LinearLayouts holding TextViews contained in a parent Layout. These LinearLayouts are going to be able to be clicked on, but the problem is...all the Layouts & Views are created from an ArrayList (from JSON on my web server) in a for loop. So I need a way to make onClickListener an array so I can have multiple listeners under the same title, doing the same thing. I could also pass variables (like the Layout ID) through to the Listener if that's possible.

For example:
Code: Select all
for(int i = 0; i<questionArray.size(); i++){
   questionLayout.add(new RelativeLayout(context));
   questionLayout.get(i).setClickable(true);
   questionLayout.get(i).setOnClickListener(questionClickListener(i));
}

private OnClickListener questionClickListener(int i) = new OnClickListener() {
   public void onClick(View v) {

   }
}; 


or:
Code: Select all
for(int i = 0; i<questionArray.size(); i++){
   questionLayout.add(new RelativeLayout(context));
   questionLayout.get(i).setClickable(true);
   questionLayout.get(i).setOnClickListener(questionClickListener[i]);
}

private OnClickListener[] questionClickListener = new OnClickListener() {
   public void onClick(View v) {

   }
}; 


I know neither of those examples works, but it just shows the idea of my code and what I want done..

Any help is much appreciated as always!
-Sam
thekooliest
Junior Developer
Junior Developer
 
Posts: 16
Joined: Wed Dec 22, 2010 11:05 pm

Top

Re: onClickListener as Array (or pass variables to Listener)

Postby thekooliest » Fri Apr 08, 2011 3:02 am

Ah I'm so proud of myself, trying a while to find a work around for this. But I used intellect to figure it out on my ownsome ;)

Just some quick sample code for other curious people:
Code: Select all
final int x = i;  // make the temporary int i from for loop into a final int, so listener can see it.
questionLayout.add(new RelativeLayout(context));
questionLayout.get(i).setClickable(true);
          questionLayout.get(i).setOnClickListener(
                new OnClickListener() {  // I just smacked the code inside here, and each one gets made separately...idk but it works ;)
                     public void onClick(View v) {
                        questionLayout.get(x).setBackgroundColor(baseColor + 0xffffff);
                     }
                 }
          );
thekooliest
Junior Developer
Junior Developer
 
Posts: 16
Joined: Wed Dec 22, 2010 11:05 pm

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 21 guests