从未调用过BaseAdapter OnItemClickListener

我有一个自定义BaseAdapter用于我的ListView ,其中我实现了AdapterView.OnItemClickListener

问题是从不调用onItemClick(AdapterView, View, int, long)方法。 我想我需要在我的主Activity实现该interface ,而不是在我的ListView自定义适配器中。

MyListViewAdapter.java

 public class MyListViewAdapter extends BaseAdapter implements AdapterView.OnItemClickListener { private Context context; private ArrayList rowsList = new ArrayList(); // All one row items private TextView a; public MyListViewAdapter(Context context,ArrayList rowsList) { this.context = context; this.rowsList = rowsList; } @Override public int getCount() { return this.rowsList.size(); } @Override public Object getItem(int position) { return this.rowsList.get(position); } @Override public long getItemId(int position) { return position; } /** * Returns a new row to display in the list view. * * Position - position of the current row. * */ @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); /** * Inflating the root view and all his children and set them to a View Object. * */ View row = layoutInflater.inflate(R.layout.list_view_row,null); // Get all the views in my row this.a = (TextView) row.findViewById(R.id.a_id; MyListViewRow myListViewRow = rowsList.get(position); // Set values to all the views in my row this.a.setText(myListViewRow.getA()); return row; } @Override public void onItemClick(AdapterView parent, View view, int position, long id) { Toast.makeText(context, "onItemClick LV Adapter called", Toast.LENGTH_LONG).show(); } } // End of MyListViewAdapter class 

我对吗?

你为什么在适配器里面有一个OnItemClickListener?! 您可以在Adapter中使用OnClickListener,或者最佳做法是将OnItemClickListener设置为ListView或您在activity / fragment中使用的任何AdapterView。 你现在这样做的方式,由于以下几个原因不起作用:

  1. 您没有将侦听器设置为视图。
  2. 不能将OnItemClickListener设置为TextView。
  3. 将onClickListener设置为适配器类内的TextView意味着您必须单击TextView本身,否则, 将不会调用该侦听器。

使用自定义适配器OnItemClickListener不起作用。 您必须在getView方法中在视图上注册onClickListener。

 public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); /** * Inflating the root view and all his children and set them to a View Object. * */ View row = layoutInflater.inflate(R.layout.list_view_row,null); // Get all the views in my row this.a = (TextView) row.findViewById(R.id.a_id; MyListViewRow myListViewRow = rowsList.get(position); // Set values to all the views in my row this.a.setText(myListViewRow.getA()); row.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // do your stuff } }); return row; }