好的,我正在尝试创建一个通用应用,在手机视图中显示3个标签,平板电脑横向显示3个标签。因此,我使用线性布局创建了几种不同的XML布局。
然而,使用片段,我遇到了一个问题 - 我想在该片段中进行选择时删除最左边的列。我相信我可以做到这一点,但事实证明我无法删除XML中声明的片段。所以现在,我想用XML创建中间和右侧列:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/menu_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<fragment
android:id="@+id/classification_fragment"
android:name="uk.colessoft.android.hilllist.fragments.MenuClassificationFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="@layout/list_classifications" >
</fragment>
<fragment
android:id="@+id/map"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
然后使用
添加第一列FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MenuCountryFragment countryFragment=new MenuCountryFragment();
fragmentTransaction.add(R.id.menu_layout, countryFragment, "country_menu").commit();
但我有两个问题:
a)上面的代码只将片段放在线性布局的右侧,我无法指定位置。它需要在左边。
b)XML让我可以根据屏幕大小/方向自由定义片段的不同权重。在Fragments中以编程方式设置布局参数似乎是一个倒退的步骤。我通过在xml中放置一个占位符视图来解决这个问题,我从中读取了布局参数并将它们分配给onCreateView,但它是一个黑客。我知道我可以通过将片段添加为xml中第一个元素的子元素来将片段放在正确的位置但是当我这样做并删除片段时会留下空白。
答案 0 :(得分:1)
为要添加的新片段(在XML中)创建一个占位符,如下所示......
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/menu_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="@+android:id/realtabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<fragment
android:id="@+id/classification_fragment"
android:name="uk.colessoft.android.hilllist.fragments.MenuClassificationFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="@layout/list_classifications" >
</fragment>
<fragment
android:id="@+id/map"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
然后,不是在运行时添加新片段,而是替换空容器的内容......
FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MenuCountryFragment countryFragment=new MenuCountryFragment();
fragmentTransaction.replace(R.id.realtabcontent, newFrag).commit();
fragmentManager.executePendingTransactions();
希望这会有所帮助。