在Fragment中添加选项卡并从MainActivity中调用

时间:2015-04-10 06:28:31

标签: android android-fragments fragment-tab-host

我想创建一个App,它有导航抽屉/ DrawerLayout,片段和带Tab的片段。

enter image description here

我希望Fragment with tab,只需在MainActivity.java中调用

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Fragment fragment=null;
        switch (position)
        {
            case 0:
               // fragment= new frag1();
                break;
            case 1:
                fragment=new tab_fragment();
                break;
        }

请帮助我,因为我是Android的新手,在此先感谢...!

2 个答案:

答案 0 :(得分:0)

嗨尝试Top Header Tabs in Fragment,只需替换MainActivity中的代码并将其添加到OnItemClick方法中

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Fragment fragment=null;
        switch (position)
        {
            case 0:
               // fragment= new frag1();
                break;
            case 1:
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new HomeFragment().commit();
                break;
        }

答案 1 :(得分:0)

在主要活动类

 private TabsPagerAdapter mAdapter;

private String[] tabsTitles = {"Ex1", "Ex2"};

onCreateView使用此

  mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), tabsTitles.length);

它呼叫TabsPagerAdapter

   public class TabsPagerAdapter extends FragmentPagerAdapter {
private int totalTabs;
public TabsPagerAdapter(FragmentManager fm,int totalTabs) {
    super(fm);
    this.totalTabs = totalTabs;
}

@Override
public Fragment getItem(int index) {

    switch (index % 3) {
    case 2:
        case 1:
        return new Ex1();
    case 0:
        return new Ex2();
    }

    return null;
}

@Override
public int getCount() {
    return totalTabs;
  }
 }