0

「i」が数字である名前に基づいて、アクティビティでいくつかのフラグメントを開始したいので... DummySection1Fragment、DummySection2Fragment、DummySection3Fragment など。電話。基本的な静的呼び出しと、JavaScript の世界から知っていることに基づいて自分で作成したものを含めました (それが私の問題だと思います)。

何度も何度も使用する可能性のある方法であると思われるため、これを行うための最良の方法について(私がまだ自分自身を見ている間)助けていただければ幸いです。

現在の静的コード

    public Fragment getItem(int i) {
    Fragment fragment = new DummySectionFragment();

エラー : 文字定数が無効です

    public Fragment getItem(int i) {
    Fragment fragment = new 'DummySection' + i + 'Fragment'();

完全なコード

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
 * sections of the app.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new DummySectionFragment();
        Bundle args = new Bundle();
        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        return 6;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0: return getString(R.string.title_section1).toUpperCase();
            case 1: return getString(R.string.title_section2).toUpperCase();
            case 2: return getString(R.string.title_section3).toUpperCase();
            case 3: return getString(R.string.title_section4).toUpperCase();
            case 4: return getString(R.string.title_section5).toUpperCase();
            case 5: return getString(R.string.title_section6).toUpperCase();
        }
        return null;
    }
}
4

1 に答える 1

1

このアプリの動作には強くお勧めします。後で#3を削除し、アイテム#4から#17がある場合はどうなりますか?または、#6と#7の間に1つ追加する必要があるかもしれません。これは多くの名前変更です(順序を維持していると仮定します)。

適切な名前を付けて、手動でインスタンス化することをお勧めします。これを行うと、それらをに保存してからArrayList<Fragment>、を返すことができます.get(i)

代わりにメソッドを実行することを完全に100%決定している場合は、次のように実行できるはずです。

Class clazz = Class.forName("DummySection" + i + "Fragment"); // Use ", not '
Fragment frag = (Fragment) clazz.newInstance();
于 2012-10-14T21:48:59.107 に答える