从mainActivity向片段添加视图

时间:2013-03-21 06:20:33

标签: android fragment android-view

我想动态地为此mainActivity中的片段添加视图 因为,Fragment类没有addView() API,我可以使用的其他选项是什么。
我在第1行尝试fragment.getView(),但它给出了nullpointer异常。我不太了解片段api,也没有时间投资于它。任何人都可以为此问题提供解决方法。

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);
}
}

2 个答案:

答案 0 :(得分:0)

尝试在活动的fragment.getView()onResume()方法中致电onStart()

答案 1 :(得分:0)

请查看此内容:One& Two