android - 如何在许多布局中包含的页脚布局中设置点击侦听器?
问题描述
晚上好。
我面临的问题可以通过以下方式描述:
- 我有很多实现相同页脚的视图(main、list_items、book_item ...)
- 例如,页脚有一些按钮(书籍项目、列表项目)。
- 我需要在页脚按钮上定义单击侦听器,以便在包含此页脚的每个布局中重用它。
到目前为止,如果我在与包含页脚的布局相关的每个活动中设置点击侦听器,我只能使页脚按钮工作。
你建议如何解决这个问题?非常感谢您的帮助和详细信息,因为我是 android 开发的新手。
我的代码类似于以下内容:
布局1.xml
<content>...</content>
<include layout="@layout/footer_layout"></include>
布局2.xml
<content>...</content>
<include layout="@layout/footer_layout"></include>
页脚.xml
<Button>List Items</Button>
<Button>Book Item</Button>
解决方案
您可以为您的 footer_layout 创建一个片段,然后添加它并在每个活动中重用它。
片段的使用将允许您完全模块化您的活动,您可以在单个活动中组合多个片段以构建像平板电脑上的多窗格 UI,并且您可以在多个活动中重用单个片段,这就是您所要做的想做。
查看文档: https ://developer.android.com/guide/components/fragments
1-创建一个页脚片段:
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- 现在您可以在所有所需的活动 xml 布局文件中包含 fragment_layout。
推荐阅读
- bash - 用 ref 替换文件中匹配的字符串到多行
- python - python代码输出未显示在Windows 10终端上
- c++ - 如何使用初始化列表来初始化 std::variant?
- c - 使用 pi 的数字时返回错误 3221225725
- javascript - 如何在数组中打印数字,同时将其与 Js 中的预定义值进行比较
- python - 我无法在我的 Windows 10 机器上启动我的 jupyter 实验室。非虚拟机笔记本电脑
- azure - 如何在 Azure 事件中心基本吞吐量上省钱
- r - 在 RMarkdown 中使用 nest 和 tidy 创建格式化的 html 回归输出
- java - 使用 Reactor WebClient 发出非阻塞 HTTP 请求并反序列化对对象的响应的最佳方法是什么?
- javascript - 初学者:Vue 错误“未定义 Vue”