[英]Listen to click on button in listview
I have a fragment with a listview in it. 我有一个带有列表视图的片段。 The listview uses a custom adapter.
列表视图使用自定义适配器。 Each item in the listview contains a button.
列表视图中的每个项目都包含一个按钮。 What I need is for the activity to know what button I press in the listview.
我需要的是活动知道我在列表视图中按下的按钮。 I need this because the fragment needs too send a message to its activity depending on what button is pressed.
我需要这样做,因为片段也需要根据其按下的按钮向其活动发送消息。 So basically I want the
OnClickListener
to be in the fragment and not in the adapter. 因此,基本上,我希望
OnClickListener
在片段中而不在适配器中。
I have tried to get the buttons from the list by itterating over all its elements and do a getChild(), but it does not react on click. 我尝试通过遍历其所有元素并执行getChild()从列表中获取按钮,但单击后不会反应。
Button theButton = (Button)theListView.getChildAt(i).findViewById(R.id.button_id);
I have also tried with the getView on the adapter. 我也尝试在适配器上使用getView。
Button theButton = (Button) adapter.getView(i, null, null).findViewById(R.id.button_id);
Set the OnClickListener in the Adapter as usual but keep a reference to your fragment! 像往常一样在适配器中设置OnClickListener,但保留对片段的引用!
Let us say that your fragment class is MyFragment. 假设您的片段类是MyFragment。 Pass your fragment to the adapter;
将片段传递给适配器; -ie in the constructor
-ie在构造函数中
private MyFragment theFragment;
public YourAdapter(MyFragment f) {
this.theFragment = f;
}
In this way you can use theFragment
in every OnClickListener you set. 这样,您可以在设置的每个OnClickListener中使用
theFragment
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.