使用切换按钮在ListView中的行的自定义视图

时间:2013-02-13 14:39:20

标签: android

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

lv.setAdapter(adapter);

lvListView,其适配器为ListView的每一行保存一个自定义视图,其中包含TextView(标签)和ToggleButton

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

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

1 个答案:

答案 0 :(得分: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;
}