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

How to set a click listener in a footer layout included in many layouts?

晚上好。

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

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

你建议如何解决这个问题? 非常感谢您的帮助和详细信息,因为我是 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>

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

片段的使用将使您能够完全模块化您的活动,您可以将多个片段组合在一个 activity 中以构建多窗格 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- 现在您可以在所有需要的活动 xml 布局文件中包含 fragment_layout。