假设我有一个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/