如何在TabLayout中查看选项卡的视图? [英] How do I get the view of a Tab in a TabLayout?

查看:94
本文介绍了如何在TabLayout中查看选项卡的视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在TabLayout中找到选项卡的视图,以便可以将其传递给另一个函数.我不确定如何去寻找风景. myTabLayout.getTabAt(0).getCustomView()返回null.

I'd like to find the view of a Tab in a TabLayout so that I can pass it to another function. I'm not sure how to go about finding the view. myTabLayout.getTabAt(0).getCustomView() returns null.

如何获取视图?

TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout_main);
tabLayout.addTab(tabLayout.newTab().setText("Page1"));
tabLayout.addTab(tabLayout.newTab().setText("Page2"));

viewPager = (ViewPager) rootView.findViewById(R.id.pager_main);
pagerAdapter = new MyPagerAdapter(getActivity(), getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);

推荐答案

我最终使用以下命令获取选项卡视图.我只是不确定这是最佳做法还是在所有Android版本中都可靠:

I ended up using the following to get tab views. I'm just not sure if it's best practice or if it's reliable across all Android versions:

mainTab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(desiredPosition);

查看源代码,我们可以看到tabLayout.getChildAt(0)返回SlidingTabStrip,这是扩展LinearLayout的内部类,其中包含标签视图.然后,您可以使用.getChildAt(desiredPosition)访问选项卡视图.请注意,在使用getChildAt()时,不会检查边界,因此请确保调用正确的索引,并检查null返回.

Looking at source we can see that tabLayout.getChildAt(0) returns the SlidingTabStrip which is an internal class extending LinearLayout that holds the tab views. Then, you can access the tab view with .getChildAt(desiredPosition). Note that when using getChildAt() boundaries are not being checked, so make sure you are calling correct indexes and also check for null returns.

这篇关于如何在TabLayout中查看选项卡的视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆