1.main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.design.widget.TabLayout android:id="@+id/tab_layout_mian" android:layout_width="match_parent" android:layout_height="60dp" android:background="@color/colorPrimaryDark" app:tabSelectedTextColor="@color/colorAccent" app:tabTextColor="@color/colorWhite" app:tabMode="fixed" app:tabIndicatorColor="@color/colorAccent"> </android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id="@+id/view_pager_main" android:layout_below="@+id/tab_layout_mian" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" > </android.support.v4.view.ViewPager> </RelativeLayout>
2.main.activity
@Bind(R.id.view_pager_main) ViewPager viewPager;// 声明一个viewpager对象 @Bind(R.id.tab_layout_mian) TabLayout tabLayout;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_call); ButterKnife.bind(this); initView(); }
/** * 添加布局ID */ private void initView() { viewPager.setAdapter(adapter); tabLayout.setTabsFromPagerAdapter(adapter); tabLayout.setupWithViewPager(viewPager); //0,第一位开始滑动,1第二位开始滑动 int currentIndex = getIntent().getIntExtra("current", 1); viewPager.setCurrentItem(currentIndex); }
/** * fragment 滑动导航适配 */ public class PhoneFragemtAdapter extends FragmentPagerAdapter {
//设置导航标题
String[] titles = new String[]{getString(R.string.text_call_re),getString(R.string.text_encryption_telephone)}; public PhoneFragemtAdapter(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { return titles[position]; } @Override public Fragment getItem(int position) { switch (position) { //两个碎片fragment case 0: return CallRecordsFragment.newFragment(); case 1: return PhoneFragment.newFragment(); } return PhoneFragment.newFragment(); } @Override public int getCount() { return titles.length; } }
public class CallRecordsFragment extends Fragment{ public static CallRecordsFragment newFragment() { CallRecordsFragment fragment = new CallRecordsFragment(); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.call_records_fragment, container, false); } }