viewPager是頁面區塊內容的切換,可通過滑動的方式進行頁面的切換。
implementation "androidx.viewpager2:viewpager2:1.0.0"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SqlLiteTest.MainActivity4"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tablayout"
app:tabRippleColor="@color/colorAccent"
app:tabIndicatorColor="@color/colorPrimary">
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/viewpager"/>
</LinearLayout>
public class BindFragmentAdapter extends FragmentPagerAdapter {
//宣告陣列
private Fragment[] mFragments;
private String[] titles;
//初始化
public BindFragmentAdapter(@NonNull FragmentManager fm,String[] titles,Fragment[] mFragments) {
super(fm);
this.mFragments=mFragments;
this.titles=titles;
}
@NonNull
@Override
public Fragment getItem(int position) { //取分頁的內容
return mFragments[position];
}
@Override
public int getCount() { //分頁數量
return mFragments.length;
}
@Override
public CharSequence getPageTitle(int position) { //取tab的名稱
return titles[position];
}
}
public class MainActivity4 extends AppCompatActivity {
private BindFragment1 bindFragment1 =new BindFragment1();
private BindFragment2 bindFragment2 =new BindFragment2();
private BindFragment3 bindFragment3 =new BindFragment3();
private Fragment[] fragments=new Fragment[3];
private TabLayout tab;
private String[] titles=new String[3];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
init();
}
private void init() {
final ViewPager viewPager=(ViewPager)findViewById(R.id.viewpager);
tab=(TabLayout)findViewById(R.id.tablayout);
//將要顯示的tab name放入titles
titles[0]="第一頁";
titles[1]="第二頁";
titles[2]="第三頁";
for (String title:titles) {
tab.addTab(tab.newTab().setText(title));
}
//將要顯示的fragment放入fragments陣列
fragments[0]=bindFragment1;
fragments[1]=bindFragment2;
fragments[2]=bindFragment3;
//將titles跟fragments傳給BindFragmentAdapter
BindFragmentAdapter adapter = new BindFragmentAdapter(getSupportFragmentManager(), titles,fragments);
//將BindFragmentAdapter與viewPager綁定
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab));//viewpager換頁時,tablayout也跟著換頁。
tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//點擊tabitem,viewpager跟著換頁;沒加這行點擊tabItem,fragment不會做換頁。
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}