标签:
效果图:
标题和fragment联动效果已经封装好了,非常方便
<android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:tabMode="scrollable"></android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id="@+id/vp" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/tabs"></android.support.v4.view.ViewPager>
配置要特别注意
dependencies { compile fileTree(dir: ‘libs‘, include: [‘*.jar‘]) testCompile ‘junit:junit:4.12‘ compile ‘com.android.support:appcompat-v7:23.1.1‘ compile ‘com.android.support:design:23.1.1‘ compile ‘com.android.support:support-v4:23.1.1‘ }
public class MyFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.myfragment,null); return view; } }
public class MyAdapter extends FragmentPagerAdapter { private List<String> titles; private List<Fragment> fragments; public MyAdapter(FragmentManager fm) { super(fm); } public MyAdapter(FragmentManager fm, List<String> titles, List<Fragment> fragments) { super(fm); this.titles = titles; this.fragments = fragments; } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return titles.size(); } @Override public CharSequence getPageTitle(int position) { return titles.get(position); } }
public class MainActivity extends AppCompatActivity { private TabLayout tabLayout; private ViewPager viewPager; private List<String> titles; private List<Fragment> fragments; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout = (TabLayout) findViewById(R.id.tabs); viewPager = (ViewPager) findViewById(R.id.vp); initTitles(); initFragments(); MyAdapter adapter = new MyAdapter(getSupportFragmentManager(), titles, fragments); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); } private void initTitles() { titles = new ArrayList<>(); for (int i = 0; i < 10; i++) { titles.add("标题" + i); } } private void initFragments() { fragments = new ArrayList<>(); for (int i = 0; i < titles.size(); i++) { fragments.add(new MyFragment()); } } }
标签:
原文地址:http://www.cnblogs.com/anni-qianqian/p/5543585.html