1. 程式人生 > >ViewPager和TabLayout互動關聯

ViewPager和TabLayout互動關聯

Activity:

	package com.example.fuxi_2;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
//定義變數
private ViewPager viewPager;
private TabLayout tab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取資源ID
viewPager=findViewById(R.id.viewpager);
tab=findViewById(R.id.tab);
//viewpager的介面卡
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));

    //tab和viewpager互動關聯之一*******
    tab.setupWithViewPager(viewPager);
    
}

}

Viewpager的介面卡:

package com.example.work9_10;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.example.work9_10.Fragment.MainFragment;

public class ViewPagerAdapter extends FragmentPagerAdapter {
private String[] menus={“我的”,“遊戲”,“視訊”};

public ViewPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override	//根據條目得到不同的fragment*******
public **Fragment** getItem(int i) {
    switch (i){
        case 0:
            return new MainFragment();
        default:
            return new Fragment();
    }
}

@Override
public int getCount() {
    return menus.length;
}

//viewpager和tab互動關聯之一***********

@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return menus[position];
}

}

XML:

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
            android:layout_above="@id/tab"
        />

    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        />
</RelativeLayout>