大家好,我正在用android中的碎片玩耍
我读到有两种方法可以在活动中绑定片段
1)在布局(XML)文件中使用<fragment>
标签
2)使用FragmentManager和FragmentTransaction
我希望我的Activity能动态处理片段,所以我选择了第二种方法
但是当添加一个片段时,它会被添加到RelativeLayout Activity的左上角(这似乎是RelativeLayout的默认行为)
我希望我的片段出现在活动布局的中心。
我只是无法弄清楚如何在JAVA代码中为fragmet提供位置。
我也查看了stackoverflow,
使用--RelativeLayout.LayoutParams
似乎与View对象一起使用(Button,TextView等) 任何建议。
答案 0 :(得分:3)
您可以在XML中的FrameLayout
内设置占位符RelativeLayout
,并将其与android:layout_centerInParent="true"
对齐。然后将此占位符替换为代码FragmentTransaction#replace(int containerViewId, Fragment fragment, String tag)
在您的活动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();
答案 1 :(得分:0)
在您的活动的布局中,使用android:layout_gravity="center"
所在的RelativeLayout
的属性Fragment
。这将使其所有子元素出现在中心。