如何将ViewPager限制在一个片段中,而不是占据整个屏幕



我正在开发的应用程序的布局是经典的两窗格主细节布局。在左窗格中为菜单,在右窗格中为按下菜单项后显示的片段。其中一个菜单项启动ViewPager滑动结构。此ViewPager结构由ScreenSlideActivity和ScreenSlide PageFragment类组成。按照标准,第一个类包含一个指向ViewPager对象的指针,该对象是具有getItem和getFragment等基本方法的适配器(ScreenSlidePagerAdapter)。

一切都很好,除了ViewPager占据了整个屏幕,而不是右侧面板。

问题:如何让ViewPager将自己限制在右侧面板,而不是占据整个屏幕

以下是two_pane的布局,由Eclipse在生成主细节模板项目时自动生成:

<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:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:baselineAligned="false"
android:divider="?android:attr/dividerHorizontal"
android:orientation="horizontal"
android:showDividers="middle"
tools:context=".ItemListActivity" >
<!--
This layout is a two-pane layout for the Items
master/detail flow. See res/values-large/refs.xml and
res/values-sw600dp/refs.xml for an example of layout aliases
that replace the single-pane version of the layout with
this two-pane version.
For more on layout aliases, see:
http://developer.android.com/training/multiscreen/screensizes.html#TaskUseAliasFilters
-->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/item_list"
android:name="com.company.ItemListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="@android:layout/list_content" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="20dip"
android:layout_marginTop="10dip"
android:layout_marginBottom="20dip"
android:src="@drawable/icon" />
</LinearLayout>
<FrameLayout
android:id="@+id/item_detail_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
</LinearLayout>

启动ViewPager的菜单项是这样做的:

Intent intent = new Intent(this, ScreenSlideNewActivity.class);
startActivity(intent);

我在这里的一篇旧文章中找到了一个解决方案的提示,但这是基于不推荐使用的ActivityGroup(底部的解决方案)。

ActivityGroup或在其他活动中使用活动的任何其他方式都是不推荐的。

您需要将ViewPager结构封装在Fragment中,而不是Activity中。

从那里开始,你只需要用一个简单的弹出你的Fragment来代替你的R.id.item_detail_container

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
ScreenSlideNewFragment fragment = new ScreenSlideNewFragment();
transaction.replace(R.id.item_detail_container, fragment);
transaction.commit();

将活动转换为片段是直接的,因为生命周期非常相似。

最新更新