目标是根据屏幕方向(纵向或横向)以不同的布局在屏幕上显示两个片段(片段 A、片段 B)。
当设备处于纵向模式时,一次只显示 Frag A 和 Frag B 中的一个,使用滑动切换 UI。ViewPager 非常适合这个。
当设备处于横向模式时,Frag A 显示在屏幕左侧,Frag B 显示在右侧。一个简单的 LinearLayout 可以完美地解决这个问题。
当试图让两者在同一个应用程序中工作时,就会出现问题。似乎必须在 Java 源代码中引用 ViewPager 类(在 onCreate 方法中)。这意味着在 XML 和源代码中都定义了一个 UI 元素......当设备处于横向模式并且不应该有 ViewPager 对象但在源代码中被引用时,这似乎是一个问题。我正确地接近这个吗?如果一个布局使用 ViewPager,那么其他所有布局都需要 ViewPager 吗?
布局/activity_mymain.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyMainActivity" >
<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.
-->
<android.support.v4.view.PagerTitleStrip
android:id="@+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
布局土地/activity_mymain.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="com.example.ActionFragment"
android:id="@+id/action_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.SummaryFragment"
android:id="@+id/summary_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
来自 MyMainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topmain);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}