5

目标是根据屏幕方向(纵向或横向)以不同的布局在屏幕上显示两个片段(片段 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);

}
4

1 回答 1

1

ViewPager 用于在运行时实例化 View 对象,因此需要在代码中定义。

我试图做的与Fragments Guide中描述的不同平板电脑/手机布局非常相似,他们建议使用单独的活动。

(如果有人知道一种完全在 XML 中处理滑动的方法,那将是一个更好的解决方案)

于 2013-02-08T14:54:32.393 回答