0
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_view_row,R.id.label,objects);

lv.setAdapter(adapter);

lv是 a ListView,它的适配器为 ListView 的每一行保存一个自定义视图,其中包含一个TextView(label) 和一个ToggleButton.

https://www.dropbox.com/s/g3gkjct6rbpcgla/Screenshot_2013-02-13-20-00-47.png?m

如何在 ListView 的每一行中为 ToggleButton 设置监听器?

4

1 回答 1

1

例如,您应该在自定义适配器的 getView() 方法中设置它们

@Override
public View getView( int position, View convertView, ViewGroup parent ){

    ReportListItem listItem = getItem( position );
    TextView reportNameTextView;
    CheckBox isCheckedCheckBox;

    if( convertView == null ) {

        //creating convert view
        convertView = layoutInflater.inflate( R.layout.report_list_item_layout, null );

        //initializing views
        reportNameTextView = (TextView) convertView.findViewById( R.id.reportListItem_reportNameTextView );
        isCheckedCheckBox = (CheckBox) convertView.findViewById( R.id.reportListItem_isCheckedCheckBox );

        //setting tag for view
        convertView.setTag( new ReportListViewHolder( reportNameTextView, isCheckedCheckBox ) );

        //setting check box on click listener
        isCheckedCheckBox.setOnClickListener( new OnClickListener() {
            public void onClick(View v) {
                CheckBox cb = (CheckBox) v;
                ReportListItem item = (ReportListItem) cb.getTag();
                item.toggleChecked();
                cb.setChecked( item.isChecked() );
            }               
        });
    } else {
        //getting views from convertViewTag
        ReportListViewHolder viewHolder = (ReportListViewHolder) convertView.getTag();
        reportNameTextView = viewHolder.getReportNameTextView();
        isCheckedCheckBox = viewHolder.getIsCheckedCheckBox();
    }

    //setting tag for check box and use this tag in on click listener
    isCheckedCheckBox.setTag( listItem );

    //initializing row views
    isCheckedCheckBox.setChecked( listItem.isChecked() );
    reportNameTextView.setText( listItem.getReportName() );

    return convertView;
}
于 2013-02-13T14:42:07.417 回答