2011-05-22 30 views
0

我目前有一个列表视图,每行有一个'下载'按钮,但我似乎无法正确设置每个按钮的动作监听器。我的代码目前设定每个按钮以同样的动作..Android - 行动监听器的动态按钮列表

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

我也有保持各书项目,并与它的getView方法下面的代码MyListAdapter一个MyListItemModel类

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

回答

0

试试这个:

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监听器改变。

http://www.javacoffeebreak.com/articles/toptenerrors.html查看编号6

+0

感谢您的支持。我现在通过在MyListItemModelClass中添加侦听器来解决它。我现在试试你的方法 – Plokoon 2011-05-22 21:35:21

+0

我刚试过你的方法,它仍然将每个按钮设置为相同的书本键:/ – Plokoon 2011-05-22 21:38:53