I tried to setup a onClickListner in a while loop like this:
View inflaterLayout;
LinearLayout myLayout = (LinearLayout)findViewById(R.id.linearLayout2);
while (counter < 5) {
inflaterLayout = LayoutInflater.from(getBaseContext()).inflate(R.layout.newplayerlayout, null);
myLayout.addView(inflaterLayout);
Button testButton = (Button) myLayout.findViewById(R.id.button2);
testButton.setId(testButtonArray[counter]);
((TextView) myLayout.findViewById(R.id.textView1)).setId(testTextArray[counter]);
testButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
((TextView) findViewById(testTextArray[counter])).setText("Hi!");
}
});
counter++;
}
And what I thought it would do is when you click any one of the testButton’s it would change the TextView next to it! But only the first button thats inflated works! Does anyone know what I’m doing wrong?
Basically what I’m trying to accomplish is, I’m inflating a layout that has a Plus Button, Minus Button and a Text View, so I want to be able to setup one onClickListener that will add and subtract from the text view without having to setup a million separate onClickListeners!
The code inside the onClick function is run when the button is clicked. It does not remember the values of the variables during each iteration of the loop, simply because it is in a different scope.
Update
The following code only uses one OnClickListener to increment or decrement the value of each corresponding TextView. You should be able to easily adapt this to your layout inflater with a better looking layout.
Addition from comment
I am going to assume that in your newplayerlayout.xml you have two Buttons (with the ids: “plus” and “minus”) and a TextView (with the id “text”). Perhaps you would implement the scheme like this: