java无法为tabLayout添加选项卡
我无法向tabLayout添加新选项卡
XML文件
<RelativeLayout
安卓:id="@+id/main_layout"
xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:app="http://schemas.安卓.com/apk/res-auto"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
tools:context="com.dailam103.messagetimer.MainActivity">
<安卓.support.design.widget.TabLayout
安卓:id="@+id/tabs"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
<安卓.support.v4.view.ViewPager xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:id="@+id/pager"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent" >
</安卓.support.v4.view.ViewPager>
</RelativeLayout>
主要活动。爪哇
package com.dailam103.messagetimer;
import 安卓.os.Bundle;
import 安卓.support.v4.view.ViewPager;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.support.v7.widget.Toolbar;
import 安卓.support.design.widget.TabLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.addTab(tabLayout.newTab().setTag(1).setText("Tab 1"));
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final TabAdapter adapter = new TabAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
错误在
表格布局。addTab(tabLayout.newTab()。设置标签(1)。setText(“表1”)
请问为什么我不能将tab添加到tabLayout
# 1 楼答案
您不需要像这样编写很长的代码
只需添加
tabLayout.setupWithViewPager(viewPager);
或代码,将有助于从任何地方设置表格布局
我的所有片段都扩展了
BaseFragment
。如果在活动中需要tablayout
,只需用BaseActivity
类替换BaseFragment
在BaseFragment或BaseActivity类中编写此代码
这样使用起来很容易