I need help creating dynamic buttons for listView items inside the adapter. Following code is my adapter getView function:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null) {
convertView = getLayoutInflater().inflate(R.layout.sell_animal_list_entry,null);
}
Animal animal = (Animal) getItem(position);
int count = 0;
int value = 0;
int age = 0;
int lifespan = 0;
int savePosition = 0;
String name = null;
lifespan = animal.getLifespan();
age = animal.getAge();
value = animal.getValue();
name = animal.getName();
savePosition = animal.getPosition();
LinearLayout buttonLayout = (LinearLayout) convertView.findViewById(R.id.buttonIncludeLayout);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Button sellButton = new Button(SellAnimalActivity.this);
sellButton.setText(getResources().getString(R.string.sellAnimalButtonText));
count = buttonLayout.getChildCount();
if (count == 0) {
final int finalSavePosition = savePosition;
sellButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
displaySellWarning(finalSavePosition);
}
});
buttonLayout.addView(sellButton, lp);
}
return convertView;
}
My problem now is that I can not sell the correct animals on button click.
I have 5 different animals inside the List. The first 3 animals work correctly,
but the 4th and 5th animal get wrong buttons to sell the first animal, even though the names are correctly looped.
EDIT:
To further explain: My ListView layout shows the name of the animal, its lifespan and age and I dynamically add a button to it. The name, age and lifespan are correctly applied for each animal.
The button is supposed to sell the animal. And it works up to animal 3 on the list. But the button for the 4th and 5th animal tries to sell the 1st animal.
When I Log.d the savePosition I get the following values:
0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,3,4
It seems weird to me that he reads the 4th and 5th entry only on the 5th loop?
After so many hours on that problem, maybe you can give me the solution hint for this, why are the 4th and 5th animals wrong?