2012-10-14 68 views
0

我想啓動幾個片段,在基於名稱的活動中'我'是一個數字,所以... 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; 
    } 
} 

回答

1

我強烈建議對這個應用程序的行爲。如果您想稍後移除#3,並且擁有#4至#17的項目,該怎麼辦?或者你可能需要在#6和#7之間加一個。這是很多重命名(假設你維持秩序)。

我建議給他們一個合適的名字,然後用手實例化它們。如果你這樣做,你可以將它們存儲在ArrayList<Fragment>中,然後返回.get(i)

如果你決心做你的方法,而不是絕對的100%,你應該能夠做到這一點是這樣的:在思想

Class clazz = Class.forName("DummySection" + i + "Fragment"); // Use ", not ' 
Fragment frag = (Fragment) clazz.newInstance(); 
+0

感謝埃裏克....目前正在與一些ADT的打例子....我粘貼了上面的完整適配器。 TBH我試圖從空白構建,所以我知道最近進行了什麼,而不是編輯.... –

+0

它已經建立的方式,它發送一個參數*給* Fragment,告訴它它是什麼數字。因此,每一個都是相同的'DummySectionFragment',但是基於'ARG_SECTION_NUMBER'參數的行爲不同。 – Eric

+0

是的......這個例子怎麼只採用這個arg並在屏幕上打印文本並改變標題。退一步說,如果我有6個不同的屏幕,我計劃 - 2是RSS,1個文本和一個構建邏輯(if/else等)的HTML,看起來很漫長,而不是調用單個片段? –