如何以编程方式选择TabLayout中的标签?
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
答案 0 :(得分:357)
如果您知道要选择的选项卡的索引,可以这样做:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);
tab.select();
即使您在没有ViewPager的情况下单独使用TabLayout,这项技术仍然有效(这是非典型的,可能是不好的做法,但我已经看过它了。)
答案 1 :(得分:72)
这就是我解决它的方法:
void selectPage(int pageIndex){
tabLayout.setScrollPosition(pageIndex,0f,true);
viewPager.setCurrentItem(pageIndex);
}
答案 2 :(得分:33)
使用此:
<android.support.design.widget.TabLayout
android:id="@+id/patienthomescreen_tabs"
android:layout_width="match_parent"
android:layout_height="72sp"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabIndicatorColor="@android:color/white"
app:tabSelectedTextColor="@color/green"/>
在OnClickListener之后:
TabLayout tabLayout = (TabLayout) findViewById(R.id.patienthomescreen_tabs);
TabLayout.Tab tab = tabLayout.getTabAt(someIndex);
tab.select();
答案 3 :(得分:19)
使用tabs.getTabAt(2).select();
答案 4 :(得分:18)
这可能不是最终解决方案,要求您将TabLayout
与ViewPager
一起使用,但这是如何我解决了它:
void selectPage(int pageIndex)
{
viewPager.setCurrentItem(pageIndex);
tabLayout.setupWithViewPager(viewPager);
}
我测试了使用此代码的性能影响有多大,首先在运行该方法时查看Android Studio中的CPU和内存监视器,然后将其与我导航时放在CPU和内存上的负载进行比较在我自己的页面之间(使用滑动手势),差异并不大,所以至少它不是一个可怕的解决方案......
希望这有助于某人!
答案 5 :(得分:12)
如果您不能使用tab.select()并且您不想使用ViewPager,您仍然可以以编程方式选择一个选项卡。如果您通过TabLayout.Tab setCustomView(android.view.View view)
使用自定义视图,则更简单。以下是两种方式。
// if you've set a custom view
void updateTabSelection(int position) {
// get the position of the currently selected tab and set selected to false
mTabLayout.getTabAt(mTabLayout.getSelectedTabPosition()).getCustomView().setSelected(false);
// set selected to true on the desired tab
mTabLayout.getTabAt(position).getCustomView().setSelected(true);
// move the selection indicator
mTabLayout.setScrollPosition(position, 0, true);
// ... your logic to swap out your fragments
}
如果您没有使用自定义视图,那么您可以这样做
// if you are not using a custom view
void updateTabSelection(int position) {
// get a reference to the tabs container view
LinearLayout ll = (LinearLayout) mTabLayout.getChildAt(0);
// get the child view at the position of the currently selected tab and set selected to false
ll.getChildAt(mTabLayout.getSelectedTabPosition()).setSelected(false);
// get the child view at the new selected position and set selected to true
ll.getChildAt(position).setSelected(true);
// move the selection indicator
mTabLayout.setScrollPosition(position, 0, true);
// ... your logic to swap out your fragments
}
使用StateListDrawable在选定和未选择的drawable之间切换或类似的颜色和/或drawables做你想要的东西。
答案 6 :(得分:12)
只需设置viewPager.setCurrentItem(index)
,关联的TabLayout就会选择相应的标签。
答案 7 :(得分:7)
你可以试着用它来解决它:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
TabLayout.Tab tab = tabLayout.getTabAt(pos);
if (tab != null) {
tab.select();
}
答案 8 :(得分:6)
试试这个
new Handler().postDelayed(
new Runnable(){
@Override
public void run() {
if (i == 1){
tabLayout.getTabAt(0).select();
} else if (i == 2){
tabLayout.getTabAt(1).select();
}
}
}, 100);
答案 9 :(得分:2)
我我使用TabLayout切换片段。它大部分都有效,除非我尝试使用tab.select()
以编程方式选择标签,我的TabLayout.OnTabSelectedListener
会触发onTabSelected(TabLayout.Tab tab)
,这会让我感到非常悲伤。我一直在寻找一种方法来进行程序化选择,而不会触发听众。
所以我改编了@kenodoggy对我使用的答案。我进一步面临一个问题,其中一些内部对象将返回null(因为它们尚未创建,因为我正在从我的片段回答onActivityResult()
,这在onCreate()
之前发生活动是singleTask
或singleInstance
)所以我写了一个详细的if / else序列,它会报告错误并在没有NullPointerException
的情况下通过,否则会触发。如果您未使用Log.e()
的替代品,我会使用Timber进行日志记录。
void updateSelectedTabTo(int position) {
if (tabLayout != null){
int selected = tabLayout.getSelectedTabPosition();
if (selected != -1){
TabLayout.Tab oldTab = tabLayout.getTabAt(0);
if (oldTab != null){
View view = oldTab.getCustomView();
if (view != null){
view.setSelected(false);
}
else {
Timber.e("oldTab customView is null");
}
}
else {
Timber.e("oldTab is null");
}
}
else {
Timber.e("selected is -1");
}
TabLayout.Tab newTab = tabLayout.getTabAt(position);
if (newTab != null){
View view = newTab.getCustomView();
if (view != null){
view.setSelected(false);
}
else {
Timber.e("newTab customView is null");
}
}
else {
Timber.e("newTab is null");
}
}
else {
Timber.e("tablayout is null");
}
}
这里,tabLayout是我的XML中绑定到TabLayout
对象的内存变量。而且我没有使用滚动标签功能,所以我也删除了它。
答案 10 :(得分:2)
为viewpager添加:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
array.clear();
switch (position) {
case 1:
//like a example
setViewPagerByIndex(0);
break;
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
//在处理程序上防止崩溃outofmemory
private void setViewPagerByIndex(final int index){
Application.getInstance().getHandler().post(new Runnable() {
@Override
public void run() {
viewPager.setCurrentItem(index);
}
});
}
答案 11 :(得分:1)
默认情况下,如果您选择一个标签,它将突出显示。如果要选择显式,请使用指定选项卡索引位置的onTabSelected(TabLayout.Tab选项卡)下的给定注释代码。此代码将使用viewpager解释选项卡选定位置上的更改片段。
public class GalleryFragment extends Fragment implements TabLayout.OnTabSelectedListener
{
private ViewPager viewPager;public ViewPagerAdapter adapter;private TabLayout tabLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new PaymentCardFragment(), "PAYMENT CARDS");
adapter.addFragment(new LoyaltyCardFragment(), "LOYALTY CARDS");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(this);
}
@Override
public void onTabSelected(TabLayout.Tab tab) {
//This will be called 2nd when you select a tab or swipe using viewpager
final int position = tab.getPosition();
Log.i("card", "Tablayout pos: " + position);
//TabLayout.Tab tabdata=tabLayout.getTabAt(position);
//tabdata.select();
tabLayout.post(new Runnable() {
@Override
public void run() {
if (position == 0) {
PaymentCardFragment paymentCardFragment = getPaymentCardFragment();
if (paymentCardFragment != null) {
VerticalViewpager vp = paymentCardFragment.mypager;
if(vp!=null)
{
//vp.setCurrentItem(position,true);
vp.setCurrentItem(vp.getAdapter().getCount()-1,true);
}
}
}
if (position == 1) {
LoyaltyCardFragment loyaltyCardFragment = getLoyaltyCardFragment();
if (loyaltyCardFragment != null) {
VerticalViewpager vp = loyaltyCardFragment.mypager;
if(vp!=null)
{
vp.setCurrentItem(position);
}
}
}
}
});
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
//This will be called 1st when you select a tab or swipe using viewpager
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
//This will be called only when you select the already selected tab(Ex: selecting 3rd tab again and again)
}
private PaymentCardFragment getLoyaltyCardFragment() {
Fragment f = adapter.mFragmentList.get(viewPager.getCurrentItem());
if(f instanceof PaymentCardFragment)
{
return (PaymentCardFragment) f;
}
return null;
}
private LoyaltyCardFragment getPaymentCardFragment() {
Fragment f = adapter.mFragmentList.get(viewPager.getCurrentItem());
if(f instanceof LoyaltyCardFragment)
{
return (LoyaltyCardFragment) f;
}
return null;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
public List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
}
答案 12 :(得分:1)
这不适用于实现了 ViewPager2 的应用程序,为此,您需要使用
viewPager2.setCurrentItem(position);
在onConfigureTab
内,如果在我们使用TabLayoutMediator时找到onConfigureTab
即
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(
tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0 : tab.setIcon(getResources().getDrawable(R.drawable.camera));
break;
case 1 : tab.setText("CHAT");
viewPager2.setCurrentItem(position); // when app starts this will be the selected tab
break;
case 2 : tab.setText("STATUS");
break;
case 3 : tab.setText("CALL");
break;
}
}
}
);
tabLayoutMediator.attach();
答案 13 :(得分:1)
如果您的默认选项卡是第一个(0)并且您碰巧切换到片段,那么您必须首次手动替换该片段。这是因为在监听器注册之前选择了选项卡。
private TabLayout mTabLayout;
...
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tablayout, container, false);
mTabLayout = view.findViewById(R.id.sliding_tabs);
mTabLayout.addOnTabSelectedListener(mOnTabSelectedListener);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.tabContent, MyFirstFragment.newInstance()).commit();
return view;
}
或者,您可以考虑调用getTabAt(0).select()
并覆盖onTabReselected
,如下所示:
@Override
public void onTabReselected(TabLayout.Tab tab) {
// Replace the corresponding tab fragment.
}
这样可行,因为您实际上是在每个选项卡上重新选择片段。
答案 14 :(得分:1)
来自不同答案的组合解决方案是:
new Handler().postDelayed(() -> {
myViewPager.setCurrentItem(position, true);
myTabLayout.setScrollPosition(position, 0f, true);
},
100);
答案 15 :(得分:1)
您应该使用viewPager来使用viewPager.setCurrentItem()
viewPager.setCurrentItem(n);
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) {
}
});
答案 16 :(得分:1)
使用TabLayout
提供的Material Components Library,只需使用selectTab
方法:
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.selectTab(tabLayout.getTabAt(index));
它需要版本1.1.0。
答案 17 :(得分:0)
Kotlin 用户:
Handler(Looper.getMainLooper()).postDelayed(
{ tabLayout.getTabAt(position).select() }, 100
)
如果需要滚动,这也会滚动您的标签布局。
答案 18 :(得分:0)
如果您将TabLayout与viewPager一起使用,则不但可以帮助您。您还可以在addOnpagelistener中使用viewpager设置TabLayout。
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
tabLayout.getTabAt(position).select();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
答案 19 :(得分:0)
TabLayout jobTabs = v.findViewById(R.id.jobTabs);
ViewPager jobFrame = v.findViewById(R.id.jobPager);
jobFrame.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(jobTabs));
这将选择标签页作为查看寻呼机的滑动页面
答案 20 :(得分:0)
科特林修复
viewPager.currentItem = 0
tabs.setupWithViewPager(viewPager)
答案 21 :(得分:0)
如果您使用不带viewPager的TabLayout,则有帮助
onItemClickListner onItemClickListner;
public void setOnItemClickListner(CommentsAdapter.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(Contact contact);//pass your object types.
}
@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
Contact contact=contactList.get(position);
final LayoutInflater inflater = ((Activity) context).getLayoutInflater();
final View outerContiner = inflater.inflate(R.layout.table_layout, parent, false);// define your layout
TextView text = (TextView) outerContiner.findViewById(R.id.tlTvName);
TextView barcode = (TextView) outerContiner.findViewById(R.id.tlTvBar);
text.setText(data.get(position).itemName);
barcode.setText(data.get(position).barcod);
outerContiner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onItemClickListner.onClick(contact);
}
});
return outerContiner;
}
答案 22 :(得分:0)
尝试这种方式。
tabLayout.setTabTextColors(getResources().getColor(R.color.colorHintTextLight),
getResources().getColor(R.color.colorPrimaryTextLight));
答案 23 :(得分:0)
如果您无法理解,此代码可以帮助您
private void MyTabLayout(){
TabLayout.Tab myTab = myTabLayout.newTab(); // create a new tab
myTabLayout.addTab(myTab); // add my new tab to myTabLayout
myTab.setText("new tab");
myTab.select(); // select the new tab
}
您也可以将其添加到您的代码中:
myTabLayout.setTabTextColors(getColor(R.color.colorNormalTab),getColor(R.color.colorSelectedTab));
答案 24 :(得分:0)
您可以使用以下功能设置TabLayout位置
public void setTab(){
tabLayout.setScrollPosition(YOUR_SCROLL_INDEX,0,true);
tabLayout.setSelected(true);
}
答案 25 :(得分:0)
这也有帮助
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
tablayout.getTabAt(i).select();
}
@Override
public void onPageScrollStateChanged(int i) {
}
});