1) 在 MainActivity 中:
第20行,调整
int Numboftabs =2;
到所需的正确数量的标签。
2) 重复教程中的第 5 步和第 6 步,但不要制作 Tab1 和 Tab2,而是制作 Tab3/4,...
基本上,您需要为每个选项卡添加一个 java 类文件 + 布局文件。所以我们开始:
制作一个tab_X.xml(X是数字/名称),内容如下
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="You Are In Tab X"
android:id="@+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
制作一个java类TabX(将X替换为选项卡的编号,或者只替换为名称)
package com.android4devs.slidingtab;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabX extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_X,container,false);
return v;
}
}
3) 编辑 ViewPagerAdapter 类
例如或 3 个选项卡而不是 2 个,更改以下内容
//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
Tab1 tab1 = new Tab1();
return tab1;
}
else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
Tab2 tab2 = new Tab2();
return tab2;
}
}
到
//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
Tab1 tab1 = new Tab1();
return tab1;
}
else if(position == 1)
{
Tab2 tab2 = new Tab2();
return tab2;
}
else if(position == 2)
{
Tab3 tab3 = new Tab3();
return tab3;
}
else if { .... } // add more as desired.
// but make sure that you use "else" instead of "else if" for the last tab.
}
进行这些更改后,一切都应该正常工作。
我想提一下,提供/编辑的代码来自 OP 问题中的教程。