基于tablayout的简单用法,写出全部示例代码
时间: 2023-04-11 19:01:21 浏览: 67
好的,以下是基于tablayout的简单用法示例代码:
XML布局文件:
```
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar" />
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
app:tabGravity="fill"
app:tabIndicatorColor="@android:color/white"
app:tabMode="fixed"
app:tabSelectedTextColor="@android:color/white"
app:tabTextColor="@android:color/white" />
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
Java代码:
```
// 设置Toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 设置ViewPager
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
// 设置TabLayout
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// 自定义TabLayout的每个Tab
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null) {
tab.setCustomView(R.layout.tab_item);
TextView tabText = tab.getCustomView().findViewById(R.id.tab_text);
tabText.setText("Tab " + (i + 1));
}
}
```
其中,MyPagerAdapter是自定义的ViewPager适配器,tab_item.xml是自定义的TabLayout每个Tab的布局文件。