java—虽然我有3个选项卡,但tablayout.getchildcount()返回1

8wigbo56  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(375)

我在viewpager中添加了3个选项卡,然后使用setupwithviewpager创建相应的选项卡:

private void setupFragments(){
    ViewPager mViewPager = findViewById(R.id.container);
    SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new SignalsFragment(),"Live Signals");
    adapter.addFragment(new FavSignalsFragment(),"Fav Signals");
    adapter.addFragment(new RemotesFragment(),"Remotes");
    mViewPager.setAdapter(adapter);

    TabLayout tabLayout = findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    System.out.println("Number Of Tabs: "+tabLayout.getChildCount());
}

它返回1我需要通过标签以太化,为它们设置onlongclicklistener。。。
感谢您的帮助。

xwbd5t1u

xwbd5t1u1#

在这里,我发现了问题和解决方案:我把tablayout的直接子对象与tabs误认为了,而tablayout对象只有一个直接子对象,它是一组tabs。因此,关键是首先提取该群体并通过其子女以太化。以下是对我有用的代码:

private void setupFragments(){
    ViewPager mViewPager = findViewById(R.id.container);
    SectionsPageAdapter adapter = new 
    SectionsPageAdapter(getSupportFragmentManager());
    adapter.addFragment(new SignalsFragment(),"Live Signals");
    adapter.addFragment(new FavSignalsFragment(),"Fav Signals");
    adapter.addFragment(new RemotesFragment(),"Remotes");
    mViewPager.setAdapter(adapter);

    TabLayout tabLayout = findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    View tabLayoutChild = tabLayout.getChildAt(0);
    ViewGroup group = (ViewGroup) tabLayoutChild;
    group.getChildAt(0).setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });
}

相关问题