5

目標は、画面の向き (縦または横) に応じて異なるレイアウトで画面に 2 つのフラグメント (フラグメント A、フラグメント B) を表示することです。

デバイスがポートレート モードの場合、スワイプを使用して UI を切り替えると、一度に Frag A と Frag B の 1 つだけが表示されます。ViewPager はこれに最適です。

デバイスが横向きモードの場合、画面の左側に Frag A が表示され、右側に Frag B が表示されます。シンプルな LinearLayout はこれに最適です。

同じアプリケーションで両方を機能させようとすると、問題が発生します。ViewPager クラスは、Java ソース コード内 (onCreate メソッド内) で参照する必要があるようです。これは、UI 要素が XML とソース コードの両方で定義されていることを意味します。これは、デバイスがランドスケープ モードであり、ViewPager オブジェクトが存在しないはずなのに、ソース コードで参照されている場合に問題のように見えます。私はこれに正しく取り組んでいますか?1 つのレイアウトが ViewPager を使用している場合、他のすべてのレイアウトには ViewPager が必要ですか?

レイアウト/アクティビティ_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