如何为列表项和列表项中的按钮设置onClickListener?

时间:2012-10-23 20:50:20

标签: android listview button

我有一个listView,其中每个列表项都有一个按钮。我想为列表项和按钮设置一个onClickListener - 我担心它只能做一个或另一个..

以下是我的适配器代码:

private class MyListAdapter extends ResourceCursorAdapter { 

    // In your ListActivity class, create a new inner class that extends ResourceCursorAdapter. 
    //This inner class is the custom CursorAdapter we will use to manage how data is bound to a list item:

    public MyListAdapter(Context context, Cursor cursor) { 
        super(context, R.layout.row_location, cursor);
    } 

    @Override
    public void bindView(View view, Context context, Cursor cursor) { 
        TextView text_first_line = (TextView) view.findViewById(R.id.location_row_item_main_text);
        TextView text_second_line = (TextView) view.findViewById(R.id.location_row_item_secondary_text);
        ImageView flagIcon = (ImageView) view.findViewById(R.id.flagIcon);

        String row_text_component = cursor.getString(cursor.getColumnIndex(RMDbAdapter.COMPONENT));
        String row_text_position = ", Position " + cursor.getString(cursor.getColumnIndex(RMDbAdapter.POSITION));
        if(row_text_position.equals(", Position Not Applicable")){
            row_text_position = "";
        }
        String row_text_action = " - " + cursor.getString(cursor.getColumnIndex(RMDbAdapter.ACTION_REQUIRED));

        text_first_line.setText(row_text_component + row_text_position + row_text_action);
        text_second_line.setText("test text, test text");

        String risk = cursor.getString(cursor.getColumnIndex(RMDbAdapter.RISK));
        if (risk.equals("Red Risk")){
            flagIcon.setImageResource(R.drawable.red_flag);
        }
        else if (risk.equals("Green Risk")){
            flagIcon.setImageResource(R.drawable.green_flag);
        }
        else if (risk.equals("No Risk")){
            flagIcon.setImageResource(R.drawable.note);
        }

    }
}

在之前的更简单的活动中,我为列表项设置了onListItemClick,但是如何设置按钮的监听器?

非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以在ListView行中拥有多个侦听器。只需设置一个像普通的OnClickListener:

button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        // Do something
    }
});

仅当您触摸相关按钮时,这将取代OnListItemClick侦听器。

另请注意Android的Romain Guy discussion adapters and efficiency