如何在许多布局中包含的页脚布局中设置单击侦听器?

问题描述 投票:0回答:1

晚上好。

我面临的问题可以通过以下方式描述:

  • 我有很多视图实现相同的页脚(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>

富特河XML

<Button>List Items</Button>
<Button>Book Item</Button>
android include onclicklistener footer
1个回答
0
投票

您可以为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布局文件中。

© www.soinside.com 2019 - 2024. All rights reserved.