Android首页tab动图,Android中TabLayout+ViewPager实现tab和页面联动效果

TabLayout+ViewPager实现tab和页面联动效果

xml中:

xmlns:app="http://schemas.android.com/apk/res-auto"

android:id="@+id/activity_main"

android:layout_width="match_parent"

android:layout_height="match_parent">

android:id="@+id/toolbar_tl_tab"

android:layout_width="match_parent"

android:layout_height="?attr/actionBarSize"

android:layout_gravity="bottom"

app:layout_scrollFlags="scroll"

app:tabIndicatorColor="@android:color/holo_green_light"

app:tabSelectedTextColor="@android:color/holo_green_light" />

android:layout_width="match_parent"

android:layout_height="1dp"

android:background="#f0f0f0" />

android:id="@+id/vp_container"

android:layout_width="match_parent"

android:layout_height="match_parent" />

代码中使用:

public class MainActivity extends AppCompatActivity {

private TabLayout toolbar_tl_tab;

private ViewPager vp_container;

private String[] titles = {"标题1", "标题2", "标题3", "标题4"};

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

init();

}

private void init() {

toolbar_tl_tab = (TabLayout) findViewById(R.id.toolbar_tl_tab);

vp_container = (ViewPager) findViewById(R.id.vp_container);

toolbar_tl_tab.setupWithViewPager(vp_container);

toolbar_tl_tab.setTabMode(TabLayout.MODE_SCROLLABLE);

vp_container.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {

@Override

public Fragment getItem(int position) {

return new PageFragment();

}

@Override

public CharSequence getPageTitle(int position) {

return titles[position];

}

@Override

public int getCount() {

return titles.length;

}

});

}

}

碎片:PageFragment

public class PageFragment extends Fragment {

@Nullable

@Override

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_page, null);

return view;

}

}

碎片xml:fragment_page.xml

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="center"

android:text="页面" />

注意:

1、模式相关

使用滚动模式,特点是超过屏幕可以滚动显示:

toolbar_tl_tab.setTabMode(TabLayout.MODE_SCROLLABLE);

使用屏幕等分模式,特点是显示tab的宽度是屏幕等分后的宽度:

toolbar_tl_tab.setTabMode(TabLayout.MODE_FIXED);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值