如何在ViewPager中将数据从片段传输到片段

时间:2014-04-22 11:38:43

标签: java android android-fragments android-viewpager pager

我有两个片段。

片段1有一个单选按钮

片段2有文本视图

那么,我应该怎样做才能在片段2的文本视图中显示“片段1中的单选按钮”?

我尝试了很多方法,但它不起作用:(

我的代码: 片段1:

    public class fragment1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.fragment_1, container,false);
    }

}

片段2:

public class fragment2 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.fragment_2, container,false);
    }

}

Main_Activity:

public class MainActivity extends FragmentActivity  {

    ViewPager pager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pager=(ViewPager)findViewById(R.id.pager);
        FragmentManager fm = getSupportFragmentManager();
        pager.setAdapter(new MyAdapter(fm));
    }
    class MyAdapter extends FragmentPagerAdapter
    {
        @Override
        public CharSequence getPageTitle(int position){
            CharSequence title = null;
            switch(position)
            {
            case 0:
                title ="Tab 1";
                break;
            case 1:
                title ="Tab 2";
                break;

            return title;
        }
        public MyAdapter(FragmentManager fm) {
            super(fm);
            // TODO Auto-generated constructor stub
        }

        @Override
        public Fragment getItem(int position) {
            // TODO Auto-generated method stub
            Fragment fragment = null;
            switch(position)
            {
            case 0:
                fragment = new fragment1();
                break;
            case 1:
                fragment = new fragment2();
                break;

            return fragment;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return 2;
        }

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

}

谢谢你的帮助!!!!!!

0 个答案:

没有答案