TabLayout 和 ViewPager的簡單使用
阿新 • • 發佈:2018-12-11
效果:
build.gradle 加入(如果編譯版本有誤,根據提示修改)
implementation 'com.android.support:design:27.1.0'
TabFragment.java
public class TabFragment extends Fragment { // v4 包 private String mTitle; public void setTitle(String title) { this.mTitle = title; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { TextView textView = new TextView(getContext()); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,30); textView.setGravity(Gravity.CENTER); textView.setText(mTitle); return textView; } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" tools:context=".MainActivity"> <android.support.design.widget.TabLayout app:tabGravity="fill" android:id="@+id/TabLayout" android:layout_gravity="bottom" android:layout_height="wrap_content" android:layout_width="match_parent"> </android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id="@+id/vp_pager" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity { ViewPager mViewPager; TabLayout TabLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { mViewPager = findViewById(R.id.vp_pager); TabLayout = findViewById(R.id.TabLayout); mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { // 設定 viewPager的標題 @Nullable @Override public CharSequence getPageTitle(int position) { return "標題"+position; } //建立 Fragment並返回 @Override public Fragment getItem(int position) { TabFragment fragment = new TabFragment(); fragment.setTitle("文字內容"+position); return fragment; } // 返回 item 的數量 @Override public int getCount() { return 3; } }); // tabLayout 與 viewPager 關聯 TabLayout.setupWithViewPager(mViewPager); TabLayout.getTabAt(0).setIcon(R.drawable.ic_launcher_round); TabLayout.getTabAt(1).setIcon(R.drawable.ic_launcher_round); TabLayout.getTabAt(2).setIcon(R.drawable.ic_launcher_round); TabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { // 需要重新指定 viewPager 的顯示 item mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } }
總結
- TabLayout 與 ViewPager 關聯使用
TabLayout.setupWithViewPager(mViewPager);
- 設定TabLayout的監聽事件,需要重新設定ViewPager的顯示item,因為 viewPager 內部也有一個監聽,導致衝突,所以需要重新制定。