Android-动态按钮列表的操作侦听器

Android-动态按钮列表的操作侦听器,android,dynamic,button,actionlistener,Android,Dynamic,Button,Actionlistener,我目前有一个listview,其中每行都有一个“下载”按钮,但我似乎无法正确设置每个按钮的操作侦听器。我的代码当前将每个按钮设置为相同的操作 List<MyListItemModel> myListModel = new ArrayList<MyListItemModel>(); .... MyListItemModel item = new MyListItemModel(); JSONObject e = catalogue.getJSONObject(i); i

我目前有一个listview,其中每行都有一个“下载”按钮,但我似乎无法正确设置每个按钮的操作侦听器。我的代码当前将每个按钮设置为相同的操作

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);
    } 
};
试试这个:

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));
    } 

};
基本上,您一直在传递对bookKey变量的引用,因此每次更改它时,每个onClick侦听器的引用都会更改


请参见第6条

谢谢。我刚刚通过在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(new String(bookKey));
    } 

};