【问题标题】:Listen to click on button in listview收听单击列表视图中的按钮
【发布时间】:2013-02-04 13:24:42
【问题描述】:

我有一个片段,里面有一个列表视图。 listview 使用自定义适配器。列表视图中的每个项目都包含一个按钮。 我需要的是让活动知道我在列表视图中按下了什么按钮。我需要这个,因为片段也需要根据按下的按钮向其活动发送消息。所以基本上我希望OnClickListener 在片段中而不是在适配器中。

我试图通过遍历所有元素并执行 getChild() 从列表中获取按钮,但它对点击没有反应。

Button theButton = (Button)theListView.getChildAt(i).findViewById(R.id.button_id);

我也尝试过使用适配器上的 getView。

Button theButton = (Button) adapter.getView(i, null, null).findViewById(R.id.button_id);

【问题讨论】:

    标签: java android listview button adapter


    【解决方案1】:

    像往常一样在适配器中设置 OnClickListener,但保留对片段的引用!

    假设您的片段类是 MyFragment。将您的片段传递给适配器; -IE。在构造函数中

    private MyFragment theFragment;
    public YourAdapter(MyFragment f) {
        this.theFragment = f;
    }
    

    通过这种方式,您可以在您设置的每个 OnClickListener 中使用theFragment

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 2021-01-02
      相关资源
      最近更新 更多