2

私は約7週間、Android用にプログラミングしています。「IceCreamSandwich」(API レベル 14) で導入された「タブ + スワイプ」のテンプレートを使用するアプリケーションを開始しました。

フラグメントに関するスタックオーバーフローについては多くの質問がありますが、特定の問題の解決策を見つけることができませんでした。

私の問題は、テンプレート「タブ + スワイプ」に 1 つの FragmentActivity があり、3 つのタブをインスタンス化し、自動生成された onCreate メソッドが次のようになることです。

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // 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 action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding tab.
    // We can also use ActionBar.Tab#select() to do this if we have a reference to the tab.
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by the adapter.
        // Also specify this Activity object, which implements the TabListener interface, as the
        // listener for when this tab is selected.
        actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }

}

各タブに 1 つずつ、3 つのフラグメントを作成したいと考えています。さまざまなフラグメント クラスから tab1.xml、tab2.xml、および tab3.xml レイアウトをどのように拡張すればよいですか? クラス「Pag​​erAdapter extends FragmentPagerAdapter」の getItem メソッドを使用する必要がありますか?

   @Override
    public Fragment getItem(int i) {
       // pseudo-code explanation
       switch (i) {
       case 0:
            inflate tab1.xml;
       case 1:
            inflate tab2.xml;
       case 2:
           inflate tab3.xml;
       }
       return fragment;
    }

ここで初めての質問ですので、ご理解いただければ幸いです。

ありがとうマイケル

4

1 に答える 1

4

getItem() メソッドはフラグメントを返す必要があります。したがって、次のようになります。

@Override
    public Fragment getItem(int i) {
       // pseudo-code explanation
       Fragment fragment;
       switch (i) {
       case 0:
            fragment = new FragmentTab1() // which inflates tab1.xml in its onCreateView() method;
       case 1:
            fragment = new FragmentTab2(); //etc.
       case 2:
            fragment = new FragmentTab3();
       }
       return fragment;
    }
于 2012-12-20T13:57:19.890 に答える