2013-03-21 63 views
0

我想動態地將視圖添加到此mainActivity中的片段。
因爲,片段類沒有addView() API,我還有哪些其他選項可用。
我在第1行嘗試了fragment.getView(),但它給出了空指針異常。我不太清楚片段api,沒有時間投資去完成它。任何人都可以提供解決問題的方法。將視圖添加到mainActivity中的片段

MainActivity.java

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    ActionBar bar = getActionBar(); 
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 
    ActionBar.Tab tabA = bar.newTab().setText("A Tab"); 
    ActionBar.Tab tabB = bar.newTab().setText("B Tab"); 
    ActionBar.Tab tabC = bar.newTab().setText("C Tab"); 

    Fragment fragmentA = new AFragmentTab(); 
    Fragment fragmentB = new BFragmentTab(); 
    Fragment fragmentC = new CFragmentTab(); 

    tabA.setTabListener(new MyTabsListener(fragmentA)); 
    tabB.setTabListener(new MyTabsListener(fragmentB)); 
    tabC.setTabListener(new MyTabsListener(fragmentC)); 

    bar.addTab(tabA); 
    bar.addTab(tabB); 
    bar.addTab(tabC); 

     //Line 1 
     //How to add a view from here to any of these fragment 
     //Or how can i modify the content of that fragment 

} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

protected class MyTabsListener implements ActionBar.TabListener { 

    private Fragment fragment; 

    public MyTabsListener(Fragment fragment) { 
     this.fragment = fragment; 
    } 

    public void onTabReselected(Tab tab, FragmentTransaction ft) { 
    } 

    public void onTabSelected(Tab tab, FragmentTransaction ft) { 
     ft.add(R.id.fragment_container, fragment, null); 
     // Or should the modification/addition of views be done here.   
    } 

    public void onTabUnselected(Tab tab, FragmentTransaction ft) { 
     // some people needed this line as well to make it work: 
     ft.remove(fragment); 
    } 
} 
} 

BFagmentTab.java

public class BFragmentTab extends Fragment 
{ 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{ 
    return inflater.inflate(R.layout.fragment_b, container, false); 
} 
} 

回答

0

試圖調用在活動的onResume()onStart()方法fragment.getView()

0

請看看這個:One & Two

+0

我的代碼幾乎與你相似,不同之處在於它不使用actionBarSherlock。並且兩者都實現相同的輸出,即片段的標籤視圖。但我沒有看到與我所要求的任何相似之處。我想反映更改/或修改 - 比如說 - 片段2中的片段1 – 2013-03-21 10:17:15

+0

更改您的代碼。 Actionbar碎片becoz我也面臨這個問題。 – 2013-03-21 10:36:15

+0

您能否提供一個主題的工作示例。例如,將任何動態內容添加到另一個活動的片段中的選項卡式視圖 – 2013-03-21 17:08:41