2011-05-22 73 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