如何创建子片段

时间:2014-11-01 14:53:56

标签: android android-fragments

我的代码fragmentviewPager代码为Tab

屏幕上的

我可以看到FragmentParentAFragmentParentBFragmentParentC每个都是一个完整的屏幕页。

我想将几个子片段添加到FragmentParentB

我试着理解它是如何工作的,我不理解成功..

我在下面的代码中添加子项的方法是创建子片段的新对象。  但是当我从儿童片段回来时,这是错误的方式 到FragmentParentB有错误。

 if(i==1)//`FragmentParentB` this the change which I do in class MyAdapter
        {
            if(Home.isMenuSelected()){

                switch (Home.currentButton) {

                case 1:
                    fragment=new ChatContactListActivity();
                    break;
                case 2:
                    fragment=new FragmentAaddNewUserAccount();
                    break;
            case 4:
                fragment=new FragmentInvitation();
                break;

                }
            }else
            fragment=new FragmentMenuChat();
        }

类MainActivity:

public class MainActivity extends FragmentActivity {

    ViewPager viewPager=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager= (ViewPager) findViewById(R.id.pager);
        FragmentManager fragmentManager=getSupportFragmentManager();
        viewPager.setAdapter(new MyAdapter(fragmentManager));
    }

}

类MyAdapter:

class MyAdapter extends FragmentStatePagerAdapter
{

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

    @Override
    public Fragment getItem(int i) {
        Fragment fragment=null;

        if(i==0)
        {
            fragment=new FragmentA();
        }
        if(i==1)
        {
            fragment=new FragmentB();
        }
        if(i==2)
        {
            fragment=new FragmentC();
        }
        return fragment;
    }

    @Override
    public int getCount() {

        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if(position==0)
        {
            return "Tab 1";
        }
        if(position==1)
        {
            return "Tab 2";
        }
        if(position==2)
        {
            return "Tab 3";
        }
        return null;
    }
}

class FragmentParentA,FragmentParentB,FragmentParentC:

public class FragmentParentA extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater,container,savedInstanceState);

        return inflater.inflate(R.layout.fragment_a, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
     }

}

0 个答案:

没有答案