【问题标题】:how to set position of fragment in center in RelativeLayout如何在RelativeLayout中设置片段在中心的位置
【发布时间】:2016-04-14 10:55:02
【问题描述】:

大家好,我在 android 中玩片段。
我读到有两种方法可以在活动中绑定片段。
1)在布局(XML)文件中使用<fragment>标签。
2) 使用 FragmentManager 和 FragmentTransaction .
我希望我的 Activity 动态处理片段,所以我采用了第二种方法。
但是当添加一个片段时,它会添加到RelativeLayout Activity的左上角(这似乎是RelativeLayout的默认行为) 我希望我的片段出现在活动布局的中心。 我只是不知道如何在 JAVA 代码中为片段提供位置。 我也研究了stackoverflow,

其中使用--RelativeLayout.LayoutParams

这似乎适用于视图对象(按钮、文本视图等)。
任何建议。

【问题讨论】:

  • 如果不查看您的代码和布局 XML 就很难说(提示:您可能想要添加这些),但简单的解决方案是添加一个 FrameLayout 作为片段容器并使用 @987654323 @ 和 layout_centerVertical="true"FrameLayout 定位在封装的 RelativeLayout 内。

标签: android android-layout android-fragments android-relativelayout


【解决方案1】:

您可以在 XML 中的 RelativeLayout 内设置一个占位符 FrameLayout,并将其与 android:layout_centerInParent="true" 对齐。然后用代码FragmentTransaction#replace(int containerViewId, Fragment fragment, String tag)中的片段替换这个占位符

在您的 Activity XML 布局中:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
    <FrameLayout
        android:id="@id/fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>
</RelativeLayout>

在您的 Activity 类中:

getFragmentManager().beginTransaction()
                .replace(R.id.fragment, new MyFragment())
                .commit();

【讨论】:

    【解决方案2】:

    在 Activity 的布局中,使用属性 android:layout_gravity="center" 表示 RelativeLayout 所在的 Fragment。这将使它的所有子元素出现在中心。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多