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

时间:2011-05-22 19:57:11

标签: android dynamic button actionlistener

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

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类,它包含每个书籍项和一个MyListAdapter,其getView方法的代码如下

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

1 个答案:

答案 0 :(得分: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 Listener都会改变它。

http://www.javacoffeebreak.com/articles/toptenerrors.html参见第6条