java - 在 Android 中捕获 ListView 项目内的项目中的事件的优雅而有效的方法

标签 java android android-listview

假设我有一个ListView。该 ListView 有项目。该项目有子项目(例如按钮)。

我使用适配器的子类来实现此目的,因此 getView() 是在 Adaptor 内部实现的。我希望在 ListView 所在的 Activity 中以某种方法接收该子项的点击事件。希望我的问题得到很好的解释。

哪种方法是最好的?

最佳答案

Which is the best approach?

我认为没有最佳方法。实现您想要的功能的一种简单而干净的方法是为子项事件实现一个通用监听器,并通过接口(interface)传递这些事件(由您的 Activity 实现):

public interface OnButtonEventListener {

    void onSubButtonClicked(int parentRowPosition);
}

您的 Activity 将实现此接口(interface)。

然后在适配器中构建一个通用监听器:

private OnButtonEventListener mBtnListener; // as you'll pass a Context to your adapter, the Activity which implements the OnButtonEventListener
private void OnClickListener mListener = new OnClickListener() {

      @Override
      public void onClick(View v) {
          Integer rowPosition = (Integer)  v.getTag();// you could pass other data as well
          mBtnListener.onButtonClicked(rowPosition);
      }

}

然后在适配器的getView方法中:

//...
Button b = ...find the Button
b.setTag(Integer.valueOf(position));
b.setOnClickListener(mListener);
//

如果您决定稍后这样做,使用这种方法也可以轻松地将事件广播添加到其他子项目的 Activity 中。

关于java - 在 Android 中捕获 ListView 项目内的项目中的事件的优雅而有效的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17833172/

相关文章:

android - 滚动列表时,ListView 中的 CheckBox 自动勾选

android - 在 ListView 中访问自定义对象

java - 跨线程通信java

java - Syslog 的 LoggerFields(输出日志优先级和堆栈跟踪)

javascript - Spring MVC 与 Mustache 发送字符串变量。

java - 如何访问netbeans构建jar文件中的文本文件?

android - 显示字符串时的 ListView 问题

android - 如何在ListActivity中引用OnListItemClick

android - 多表 Realm 查询

android - Listview 的页脚 View 未显示在一台设备上,而是显示在另一台设备上?