|
| 1 | +package com.rae.cnblogs.activity; |
| 2 | + |
| 3 | +import android.os.Bundle; |
| 4 | +import android.support.design.widget.TabLayout; |
| 5 | +import android.support.v4.app.Fragment; |
| 6 | +import android.support.v4.view.ViewPager; |
| 7 | +import android.view.View; |
| 8 | +import android.widget.TextView; |
| 9 | + |
| 10 | +import com.rae.cnblogs.R; |
| 11 | +import com.rae.cnblogs.fragment.HomeFragment; |
| 12 | +import com.rae.core.fm.RaeFragmentAdapter; |
| 13 | + |
| 14 | +import butterknife.BindView; |
| 15 | + |
| 16 | +public class MainActivity extends BaseActivity { |
| 17 | + |
| 18 | + @BindView(R.id.vp_main) |
| 19 | + ViewPager mViewPager; |
| 20 | + |
| 21 | + @BindView(R.id.tab_main) |
| 22 | + TabLayout mTabLayout; |
| 23 | + |
| 24 | + private RaeFragmentAdapter mFragmentAdapter; |
| 25 | + |
| 26 | + @Override |
| 27 | + protected void onCreate(Bundle savedInstanceState) { |
| 28 | + super.onCreate(savedInstanceState); |
| 29 | + setContentView(R.layout.activity_main); |
| 30 | + bindView(); |
| 31 | + |
| 32 | + mFragmentAdapter = new RaeFragmentAdapter(getSupportFragmentManager()); |
| 33 | + |
| 34 | + // 初始化TAB |
| 35 | + addTab(R.string.tab_home, R.drawable.tab_home, new HomeFragment()); |
| 36 | + addTab(R.string.tab_news, R.drawable.tab_news, new HomeFragment()); |
| 37 | + addTab(R.string.tab_library, R.drawable.tab_library, new HomeFragment()); |
| 38 | + addTab(R.string.tab_mine, R.drawable.tab_mine, new HomeFragment()); |
| 39 | + |
| 40 | + mViewPager.setOffscreenPageLimit(4); |
| 41 | + mViewPager.setAdapter(mFragmentAdapter); |
| 42 | + |
| 43 | + // 联动 |
| 44 | + mTabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager)); |
| 45 | + mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout)); |
| 46 | + |
| 47 | + } |
| 48 | + |
| 49 | + private void addTab(int resId, int iconId, Fragment fragment) { |
| 50 | + TabLayout.Tab tab = mTabLayout.newTab(); |
| 51 | + View tabView = getLayoutInflater().inflate(R.layout.tab_view, null); |
| 52 | + TextView v = (TextView) tabView.findViewById(R.id.tv_tab_view); |
| 53 | + v.setText(resId); |
| 54 | + v.setCompoundDrawablesWithIntrinsicBounds(0, iconId, 0, 0); |
| 55 | + tab.setCustomView(tabView); |
| 56 | + mTabLayout.addTab(tab); |
| 57 | + mFragmentAdapter.add(getString(resId), fragment); |
| 58 | + } |
| 59 | +} |
0 commit comments