0

我想从这个 mainActivity 动态添加一个视图到片段。
因为, Fragment 类没有addView()API,我还有其他可用的选项。
我在第 1 行尝试过fragment.getView(),但它给出了空指针异常。我不太了解 Fragment 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);
}
}
4

2 回答 2

0

尝试调用fragment.getView()活动的onResume()oronStart()方法。

于 2013-03-21T07:07:41.593 回答
0

请看这个:

于 2013-03-21T07:11:22.033 回答