Android - Action Listeners for a list of dynamic buttons
I currently have a listview where each row has a 'download' button but I cannot seem to be able to set the action listener for each button correctly. My code currently sets EVERY button to the same action..
List<MyListItemModel> myListModel = new ArrayList<MyListItemModel>();
....
MyListItemModel item = new MyListItemModel();
JSONObject e = catalogue.getJSONObject(i);
item.id = i;
item.key = e.getString("key");
bookKey = (e.getString("key"));
item.setTitle(e.getString("title"));
item.setDescription(e.getString("description"));
// change the button action to the right download address
item.listener = new OnClickListener(){
public void onClick (View v){
downloadBook(bookKey);
}
};
I also have a MyListItemModel class which holds each book item AND a MyListAdapter with the开发者_StackOverflow中文版 following code for its getView method
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
//convertView = renderer;
convertView = mInflater.inflate(R.layout.shelfrow, null);
}
MyListItemModel item = items.get(position);
TextView label = (TextView)convertView.findViewById(R.id.item_title);
label.setText(item.getTitle());
TextView label2 = (TextView)convertView.findViewById(R.id.item_subtitle);
label2.setText(item.getDescription());
Button button = (Button)convertView.findViewById(R.id.btn_download);
button.setOnClickListener(item.listener);
return convertView;
}
Try this:
MyListItemModel item = new MyListItemModel();
JSONObject e = catalogue.getJSONObject(i);
item.id = i;
item.key = e.getString("key");
bookKey = (e.getString("key"));
item.setTitle(e.getString("title"));
item.setDescription(e.getString("description"));
// change the button action to the right download address
item.listener = new OnClickListener(){
public void onClick (View v){
downloadBook(new String(bookKey));
}
};
Basically you've been passing a reference to the bookKey variable and so each time you change it it will change for each onClick Listener.
http://www.javacoffeebreak.com/articles/toptenerrors.html See number 6
精彩评论