如何在Android的TabLayout中实现动画效果?

3
我已经用一个viewPager实现了一个具有四个选项卡的TabLayout。 每个选项卡都有一个customView,因为每个选项卡有两个textView(文本+未读计数)。 所以,当切换选项卡时,我能够处理很多UI方面的内容,但是我无法对未读的textView进行动画处理。
我的自定义XML文件中,针对textView及其父RelativeLayout,都设置了android:animateLayoutChanges="true"。
此外,我尝试在实际选项卡上设置此功能,并尝试了各种动画变化,但是没有一种有效。
PS- 没有动画的情况下,我只是设置了可见性(gone,visible),这种方法是起作用的。
private void updateUnseenOnTab(int position, int unseen) {
    ViewGroup vg = (ViewGroup) mTabLayout.getChildAt(0);

    ViewGroup vgTab = (ViewGroup) vg.getChildAt(position);
    View view = vgTab.getChildAt(0);

    if (view != null && view.findViewById(R.id.tab_unseen) instanceof TextView) {
        final TextView unseenText = (TextView) view.findViewById(R.id.tab_unseen);
        if (unseen <= 0) {
            unseenText.setText("0");
            Animation fadeOut = new AlphaAnimation(0, 1);
            fadeOut.setDuration(1000);
            unseenText.setAnimation(fadeOut);
        } else {
            String currentText = unseenText.getText().toString();
            try {
                Animation fadeIn = new AlphaAnimation(0, 1);
                fadeIn.setDuration(1000);
                unseenText.setAnimation(fadeIn);
                unseenText.setText("" + ((TextUtils.isEmpty(currentText) ? 0 : unseen) + Integer.valueOf(currentText)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

你搞定了吗? - Markus
@Markus - 很遗憾,动画似乎无法在这些视图中以那种方式工作。 - Dus
这里的答案可能会有所帮助:https://dev59.com/pX7aa4cB1Zd3GeqPxf1g 我成功通过这种方式淡出了标签。 - Markus
谢谢,我会去看看。 - Dus
3个回答

2

我不知道你是想给每个选项卡添加动画,还是想给选项卡内的每个子视图添加动画。以下代码会让每个选项卡依次以150ms的延迟进行动画。如果你想给选项卡内的每个子视图添加动画,只需再加上一个循环即可。

            tabs = (TabLayout) findViewById(R.id.tabs);
            ViewGroup vg = (ViewGroup) tabs.getChildAt(0);
            int tabsCount = vg.getChildCount();
            for (int i = 0; i < tabsCount; i++)
            {
                int delay = (i * 150) + 750; //this is starting delay
                ViewGroup vgTab = (ViewGroup) vg.getChildAt(i);
                vgTab.setScaleX(0f);
                vgTab.setScaleY(0f);

                vgTab.animate()
                        .scaleX(1f)
                        .scaleY(1f)
                        .setStartDelay(delay)
                        .setInterpolator(new FastOutSlowInInterpolator())
                        .setDuration(450)
                        .start();
            }

1

这不是问题所在。你应该在回答之前先阅读问题。我是在问选项卡本身的动画。 - Dus

1
为了在每个选项卡内部动画显示视图,您可以首先像这样为每个选项卡设置自定义视图
tabLayout.getTabAt(0).setCustomView(R.layout.custom_view);

现在,您可以像这样扩展custom_view中的每个项目。
View tabView = mTabLayout.getTabAt(0).getCustomView();
TextViewPlus tabText = (TextViewPlus)tabView(R.id.tab_text);
tabText.setScaleX(1.5f);

现在你可以在选中选项卡或任何其他事件时调用动画。
请注意,您可能需要更新到构建工具v23才能使用getCustomView()

它能在较低版本的安卓系统上运行吗,例如KitKat、ICS等? - Vivek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接