如何向片段添加按钮?

How do I add a button to a fragment?

我如何向我的片段添加一个按钮,当您触摸它时,使主要 activity 切换到另一个片段。我在网上寻找教程,但他们不清楚。感谢您的帮助!

您必须在片段中维护对 MainActivity 的回调,并让 MainActivity 实现一个执行实际切换的方法。我要做的是有一个名为 MainActivity mActivityCallback 的实例变量,然后通过说 mActivityCallback = (MainActivity)getActivity() 在片段的 onCreate() 方法中分配它。然后在调用mActivityCallback.switchFragments()的按钮上添加一个OnClickListener()。在 switchFragments() 中,您可以根据需要使用 FragmentManagerFragmentTransactions 来切换片段。至于第二个问题,我不知道如何在 Android studio 中进行 - 但在 Eclipse ADT 中,您单击 XML 布局文件,它会在 GUI 编辑器中弹出。

我可以建议您从 Android 教程开始。您将自己学习许多问题的答案。这是 Google、Building a Simple User Interface 中的一个 link。教程的片段如下。检查按钮元素:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
      <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" />
</LinearLayout>