在android studio中重用片段并获取制表位置

时间:2016-08-31 05:27:28

标签: android android-studio android-fragments android-tabbed-activity

我有一个tabbedapplication。所有选项卡中的布局都相同。但根据json的反应,内容会有所不同。所以我试图在所有视图中创建单个片段并重用。但我不知道如何获得标签位置。这样我就可以调用不同的Web服务。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_fragment_all_employee, container, false);
    recyclerView_allemp = (RecyclerView) view.findViewById(R.id.recyclerview_allemp);
    recyclerView_allemp.setLayoutManager(new LinearLayoutManager(getActivity()));
// need to get the tabposition 
    new EmployeeTask().execute("http://something.com");
    return view;
} 

ViewPager oncreate:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity_employee_screen);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    mViewPager = (ViewPager) findViewById(R.id.container);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

    tabLayout.addTab(tabLayout.newTab().setText("ALL EMPLOYEES"));
    tabLayout.addTab(tabLayout.newTab().setText("MALE EMPLOYEES"));
    tabLayout.addTab(tabLayout.newTab().setText("FEMALE EMPLOYEES"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager= (ViewPager) findViewById(R.id.container);
    final PagerAdapter adapter=new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}

1 个答案:

答案 0 :(得分:0)

使用以下代码,您可以获取viewpager的当前位置:

int position = mViewPager.getCurrentItem();
Fragment fragment = adapter.getItem(position);

因此,根据位置,您可以决定哪些内容与该片段有关。