1

我有一个 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,但是如何为按钮设置侦听器?

非常感谢帮助!

4

1 回答 1

0

ListView 行中可以有多个侦听器。只需像往常一样设置一个 OnClickListener :

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

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

另请观看 Android 的 Romain Guy讨论适配器和效率

于 2012-10-23T20:55:20.273 回答