【问题标题】:How to set a click listener in a footer layout included in many layouts?如何在许多布局中包含的页脚布局中设置点击侦听器?
【发布时间】:2019-06-28 12:21:42
【问题描述】:

晚上好。

我面临的问题可以这样描述:

  • 我有许多实现相同页脚的视图(main、list_items、 book_item...)
  • 例如,页脚有一些按钮(书籍项目、列表项目)。
  • 我需要在页脚按钮上定义点击监听器 我可以在包含此页脚的每个布局中重复使用它。

到目前为止,如果我在与包含页脚的布局相关的每个活动中设置点击侦听器,我只能使页脚按钮工作。

您建议如何解决这个问题? 非常感谢您的帮助和详细信息,因为我是 android 开发的新手。

我的代码如下所示:

Layout1.xml

<content>...</content>
<include layout="@layout/footer_layout"></include>

Layout2.xml

<content>...</content>
<include layout="@layout/footer_layout"></include>

footer.xml

<Button>List Items</Button>
<Button>Book Item</Button>

【问题讨论】:

  • 您想为所有页脚布局共享一个通用侦听器吗?
  • 是的。但我想澄清一下,我的所有视图只使用 1 个页脚,并且我希望该页脚能够处理单击按钮,而无需在包含页脚的每个视图中设置单击侦听器。

标签: android include onclicklistener footer


【解决方案1】:

您可以为您的 footer_layout 创建一个片段,然后添加它并在每个活动中重复使用它。

片段的使用将允许您完全模块化您的活动,您可以将多个片段组合在一个活动中以构建一个多窗格的 UI,就像在平板电脑上一样,您可以在多个活动中重用单个片段,这就是你想做。

查看文档: https://developer.android.com/guide/components/fragments

1- 创建一个 FooterFragment:

public class FooterFragment extends Fragment {

  //Mandatory constructor for instantiating the fragment
  public FooterFragment() {
  }
  /**
     * Inflates the fragment layout file footer_layout
     */
  @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.footer_layout, container, false);

        // write your buttons and the OnClickListener logic
        ...

        // Return the rootView
        return rootView;
    }
}

2- 创建你的 fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/footer_fragment"
    android:name="com.example.android.FooterFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

3- 现在您可以将 fragment_layout 包含在所有所需的活动 xml 布局文件中。

【讨论】:

  • 感谢您的回复,虽然片段使用的描述似乎是我要找的,但我不确定是否能回答手头的问题。基本上,我需要一个包含在许多视图中的页脚来处理包含它的每个视图中的按钮单击事件。 (在多个活动之间切换)当我阅读片段时,我的理解是它们是一种对 UI 进行分段的方式,因此我们不需要在活动之间切换。请纠正我,因为我知道我可能仍然会出错。
  • 您好!如果点击侦听器将在您想要包含它的所有活动中做同样的事情,我认为片段将通过在其他活动中重用它来很好地工作。我将编辑我之前的答案,并举例说明如何做到这一点。
  • 嗨,塔里克。我能够使用片段解决问题。对我来说不明显的是,我必须使用两个 Fragment FragmentActivity 类来实现最终结果。
  • 太好了! :)
猜你喜欢
  • 2021-05-23
  • 2018-05-25
  • 1970-01-01
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多