TabLayout頁面切換教學(Part1)
上一篇已經把所有xml定義完了,接下來就要來寫code囉!
●建立一個ViewPager的容器 new->java.class
Name:ViewPagerAdapter
Superclass:
android.support.v4.app.FragmentPagerAdapter(要繼承介面改寫)
package com.example.andy6804tw.tabbed;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
/**
* Created by andy6804tw on 2016/12/6.
*/
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment>fragments=new ArrayList<>();
ArrayList<String>tabTitles=new ArrayList<>();
public void addFragments(Fragment fragment,String titles){
this.fragments.add(fragment);
this.tabTitles.add(titles);
}
public ViewPagerAdapter(FragmentManager fm){
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
●新增一個FragmentActivity
include fragment factory method和include interface callbacks勾選掉
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.andy6804tw.tabbed.HomeFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="HomeFragment"
android:layout_gravity="center"
android:textSize="30dp"
android:textStyle="bold"/>
</FrameLayout>
重複這樣分別建立HomeFragment、FirstFragment、SecondFragment
●在MainActivity.java中
package com.example.andy6804tw.tabbed; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; private ViewPagerAdapter viewPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar=(Toolbar)findViewById(R.id.app_bar); setSupportActionBar(toolbar); tabLayout=(TabLayout)findViewById(R.id.tabLayout); viewPager=(ViewPager)findViewById(R.id.viewPager); viewPagerAdapter=new ViewPagerAdapter(getSupportFragmentManager()); viewPagerAdapter.addFragments(new HomeFragment(),"Home"); viewPagerAdapter.addFragments(new FirstFragment(),"First"); viewPagerAdapter.addFragments(new SecondFragment(),"Second"); viewPager.setAdapter(viewPagerAdapter); tabLayout.setupWithViewPager(viewPager); } }
執行結果