直接搬代码过来了
//这里写在前面
@InjectView(R.id.fl_frame)
FrameLayout mFrame;
@InjectView(R.id.tv_top)
TextView tvLoginTop;
private List<Fragment> fragments;
private OnlineFragment onlineFragment;
private OfflineFragment offlineFragment;
private FragmentManager manager;
//这里写在onCreate
manager = getSupportFragmentManager();
//bundle1可以给fragment传值
Bundle bundle1 = new Bundle();
onlineFragment = new OnlineFragment();
offlineFragment = new OfflineFragment();
onlineFragment.setArguments(bundle1);
offlineFragment.setArguments(bundle1);
fragments = new ArrayList<Fragment>();
fragments.add(onlineFragment);
fragments.add(offlineFragment);
//添加tab文字
ArrayList<String> titles = new ArrayList<>();
titles.add(getString(R.string.online));
titles.add(getString(R.string.offline));
for (int i = 0; i < titles.size(); i++) {
mTbGoodsList.addTab(mTbGoodsList.newTab().setText(titles.get(i)));
}
//绑定TabLayout和FrameLayout
manager.beginTransaction()
.add(R.id.fl_frame, fragments.get(0))
.commit();
//选中的样式,layout是字体样式,放在下面
final TextView tabSelectView = (TextView) LayoutInflater.from(当前Activity.this).inflate(R.layout.tablayout_select, null);
tabSelectView.setTextSize(16);//字体大小
tabSelectView.setText(R.string.online);//设置文字
//设置默认第一个选中且设置样式
mTbGoodsList.getTabAt(0).setCustomView(tabSelectView);
//点击tablayout的点击事件
mTbGoodsList.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
//点击
switchFragment(tab.getPosition());
tabSelectView.setText(tab.getText());
tab.setCustomView(tabSelectView);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
//没有被点击
tab.setCustomView(null);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
//重新被点击
}
});
//方法类,用于切换fragment
private void switchFragment(int position) {
FragmentTransaction transaction = manager.beginTransaction();
Fragment showFragment = fragments.get(position);
Fragment hideFragment = fragments.get(hide);
if (!showFragment.isAdded()) {
transaction.add(R.id.fl_frame, showFragment);
}
transaction.show(showFragment);
transaction.hide(hideFragment);
transaction.commit();
hide = position;
}
对应的acvtivity的样式(仅供参考)
<com.google.android.material.tabs.TabLayout
android:id="@+id/tb_goods_list"
android:layout_width="match_parent"
android:layout_height="44dp"
app:tabGravity="fill"
app:tabMaxWidth="0dp"
app:tabMode="fixed"
app:tabTextAppearance="@style/TabLayoutTextStyle" />
<FrameLayout
android:id="@+id/fl_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
我的R.layout.tablayout_select的xml样式(仅供参考)
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:textSize="18sp"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginHorizontal="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
如果有什么不懂的可以私信或者在下面评论嗷