如何为ListView绑定到自定义适配器设置onClickListener?

时间:2012-04-05 20:14:42

标签: java android

这是我要在:

中实现onClickListener的类
private void updateUserListView(DatabaseHandler dbh) {
    List<User> users = dbh.getAllUsers();
    ListView listView = (ListView) findViewById(R.id.userslistview);
    listView.setAdapter(new UserArrayAdapter(BeerFriendActivity.this, users));      
}

适配器代码为:

public class UserArrayAdapter extends ArrayAdapter<User> {
private final Context context;
private final List<User> values;

public UserArrayAdapter(Context context, List<User> values) {
    super(context, R.layout.userrow, values);
    this.context = context;
    this.values = values;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final int pos = position;
    final Context con = context;
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.userrow, parent, false);
    Button button = (Button) rowView.findViewById(R.id.userrowbutton);
    TextView textView = (TextView) rowView.findViewById(R.id.userrownametext);
    textView.setText(values.get(position).getName());

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(context,BeerSearchActivity.class); 
            Bundle b = new Bundle();
            b.putInt("id", values.get(pos).getId());
            myIntent.putExtras(b); //Put your id to your next Intent
            con.startActivity(myIntent);
        } 
    });

    User user = values.get(position);
    return rowView;
}}

我尝试过实现点击器,但我得到的只是一堆错误。我已经阅读了很多教程和类似的问题,但没有一个答案似乎适合我的情况,或者我不太了解它们。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

ListView实际上并没有设置为具有可点击控件,onClick()方法使用touchEvent而不是行。但是有一种解决方法,您可以在XML中为按钮或其他可点击元素指定自定义回调,例如在this example中。

答案 1 :(得分:0)

问题是按钮的焦点。你应该在每一行中使用其他View而不是按钮(例如ImageView)并将onItemClickListener设置为listView