ViewPagerIndicator与ViewPager实现Tab

Android Studio 导入viewpagerindector最简单的方法:


根build.gradle下加maven那一行


allprojects {


    repositories {


        ...


        maven { url "https://jitpack.io" }


    }


}


在另外的build.gradle中加编译compile那一行


dependencies {


  ...


       compile 'com.github.JakeWharton:ViewPagerIndicator:2.4.1@aar'


}


最后sync


来自 http://www.imooc.com/video/5905 侵删


top.xml




    

    



TabFragment.java

@SuppressLint("ValidFragment")
public class TabFragment extends Fragment {

    private int pos;

    public TabFragment(int pos) {
        this.pos = pos;
    }

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

        View view = inflater.inflate(R.layout.frag, container, false);

        TextView tv = (TextView) view.findViewById(R.id.id_tv);

        tv.setText(TabAdapter.TITLES[pos]);

        return view;

    }
}



frag.xml




    



TabAdapter.java

public class TabAdapter extends FragmentPagerAdapter {

    public static String[] TITLES = new String[]{"课程", "问答", "求课", "学习", "计划"};


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

    @Override
    public CharSequence getPageTitle(int position) {
        return TITLES[position];
    }

    @Override
    public Fragment getItem(int position) {

        TabFragment fragment = new TabFragment(position);

        return fragment;
    }

    @Override
    public int getCount() {
        return TITLES.length;
    }
}


MainActivity

public class MainActivity extends FragmentActivity {

    private ViewPager mViewPager;

    private TabPageIndicator mTabPageIndicator;

//    private List mFragments;

    private TabAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        initView();

    }

    private void initView() {

        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);

        mTabPageIndicator = (TabPageIndicator) findViewById(R.id.id_indicator);

        mAdapter = new TabAdapter(getSupportFragmentManager());

        mViewPager.setAdapter(mAdapter);

        mTabPageIndicator.setViewPager(mViewPager, 0);

    }
}


activity_main.xml




    

    
    

    
    



style.xml



    
    

    
    

    

    

    



application的为android:theme="@style/AppTheme"


activity的为android:theme="@style/MyTheme"


ViewPagerIndicator与ViewPager实现Tab_第1张图片






你可能感兴趣的:(Android,Tab)