Android ViewSwitcher 的使用

ViewSwitcher

ViewSwitcher 代表了视图切换组件, 本身继承了FrameLayout ,可以将多个View叠在一起 ,每次只显示一个组件.当程序控制从一个View切换到另个View时,ViewSwitcher 支持指定动画效果。

ViewAnimator是一个基类,它继承了 FrameLayout,因此它表现出FrameLayout的特征,可以将多个View组件叠在一起。 ViewAnimator额外增加的功能正如它的名字所暗示的一样,ViewAnimator可以在View切换时表现出动画效果。

iewAnimator及其子类的继承关系图如下图所示:

image.png

ViewAnimator
ViewAnimator及其子类也是一组非常重要的UI组件,这种组件的主要功能是增加动画效果,从而使界面更加炫。使用ViewAnimator 时可以指定如下常见XML属性。

  • android:animateFirstView:设置ViewAnimator显示第一个View组件时是否使用动画。
  • android:inAnimation:设置ViewAnimator显示组件时所使用的动画。
  • android:outAnimation:设置ViewAnimator隐藏组件时所使用的动画。

ViewSwitcher继承ViewAnimator,主要用于视图的切换:

public class ViewSwitcher extends ViewAnimator {

}

ViewSwitcher重写了addView(View, int, ViewGroup.LayoutParams)方法,使其子控件不超过2个:

   /**
     * {@inheritDoc}
     *
     * @throws IllegalStateException if this switcher already contains two children
     */
    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        if (getChildCount() >= 2) {
            throw new IllegalStateException("Can't add more than 2 views to a ViewSwitcher");
        }
        super.addView(child, index, params);
    }

通过配置属性指定切换动画:

  1. android:inAnimation指定进入时动画
  2. android:outAnimation指定退出时动画

调用ViewSwitcher的showNext()和showPrevious()来实现视图的切换。

setFactory设置视图

ViewSwitcher中setFactory(ViewFactory)方法设置了子视图,调用obtainView()方法添加了两个子控件。

public void setFactory(ViewFactory factory) {
    mFactory = factory;
    obtainView();
    obtainView();
}

private View obtainView() {
    View child = mFactory.makeView();
    LayoutParams lp = (LayoutParams) child.getLayoutParams();
    if (lp == null) {
        lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }
    addView(child, lp);
    return child;
}

    public interface ViewFactory {
        /**
         * Creates a new {@link android.view.View} to be added in a
         * {@link android.widget.ViewSwitcher}.
         *
         * @return a {@link android.view.View}
         */
        View makeView();
    }

ViewSwitcher的使用

切换图片案例:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".activity.ViewSwitcherDemoActivity">

        <!-- ViewSwitcher子控件不能超过2个 -->
        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inAnimation="@anim/anim_enter_from_bottom"
            android:outAnimation="@anim/anim_exit_to_top"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:scaleType="fitXY"
                android:src="@drawable/pic1" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:scaleType="fitXY"
                android:src="@drawable/pic2" />

        </ViewSwitcher>

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/btn_next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="showNext"
            android:textAllCaps="false"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/view_switcher" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
public class ViewSwitcherDemoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_switcher_demo);

        ActivityViewSwitcherDemoBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_view_switcher_demo);

        binding.btnNext.setOnClickListener(v -> {
            binding.viewSwitcher.showNext();
        });
    }
}

进入动画anim_enter_from_bottom.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:duration="1000"
        android:fromYDelta="100%p"
        android:toYDelta="0%" />

</set>

退出动画anim_exit_to_top.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0"
    android:toYDelta="-100%"
    android:duration="1000" />

动态给ViewSwitcher添加子View

       //动态给ViewSwitcher添加子View
        binding.viewSwitcher.setFactory(() -> {
            ImageView iv = new ImageView(ViewSwitcherDemoActivity.this);
            iv.setImageResource(R.drawable.pic1);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setLayoutParams(new FrameLayout.LayoutParams(-1, Utils.dip2px(200)));
            return iv;
        });

        binding.btnNext.setOnClickListener(v -> {
            if (binding.viewSwitcher.getDisplayedChild() == 0) {
                ImageView iv = (ImageView) binding.viewSwitcher.getChildAt(1);
                iv.setImageResource(R.drawable.pic2);
                binding.viewSwitcher.showNext();
            } else {
                binding.viewSwitcher.showPrevious();
            }
        });

多个视图切换

有多个视图需要时,需要自定义next()和previous()方法。

为了给ViewSwitcher 添加多个组件, 一般通过ViewSwitcher 的setFactory 方法为止设置ViewFactory ,并由ViewFactory为之创建View 即可.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".activity.ViewSwitcherDemoActivity">

        <!-- ViewSwitcher子控件不能超过2个 -->
        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inAnimation="@anim/anim_enter_from_bottom"
            android:outAnimation="@anim/anim_exit_to_top"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent">

        </ViewSwitcher>

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/btn_next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="showNext"
            android:textAllCaps="false"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/view_switcher" />

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/btn_previous"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="showPrevious"
            android:textAllCaps="false"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/btn_next" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
public class ViewSwitcherDemoActivity extends AppCompatActivity {

    private ActivityViewSwitcherDemoBinding mBinding;

    private int[] mResIdArray = {
            R.drawable.pic1,
            R.drawable.pic2,
            R.drawable.pic3
    };

    private int mCount = mResIdArray.length;

    private int mPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_switcher_demo);

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_view_switcher_demo);

        mBinding.viewSwitcher.setFactory(() -> {
            ImageView iv = new ImageView(ViewSwitcherDemoActivity.this);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setImageResource(mResIdArray[0]);
            iv.setLayoutParams(new FrameLayout.LayoutParams(-1, Utils.dip2px(200)));
            return iv;
        });

        //下一张
        mBinding.btnNext.setOnClickListener(v -> next());

        //上一张
        mBinding.btnPrevious.setOnClickListener(v -> previous());

    }

    private void next() {
        ++mPosition;
        setSelection((ImageView) mBinding.viewSwitcher.getNextView());

        mBinding.viewSwitcher.setInAnimation(this, R.anim.anim_enter_from_bottom);
        mBinding.viewSwitcher.setOutAnimation(this, R.anim.anim_exit_to_top);
        mBinding.viewSwitcher.showNext();
    }

    private void previous() {
        --mPosition;
        setSelection((ImageView) mBinding.viewSwitcher.getNextView());

        mBinding.viewSwitcher.setInAnimation(this, R.anim.anim_enter_from_top);
        mBinding.viewSwitcher.setOutAnimation(this, R.anim.anim_exit_to_bottom);
        mBinding.viewSwitcher.showPrevious();
    }

    private void setSelection(ImageView imageView) {
        if (mPosition < 0) {
            mPosition = mCount - 1;
        } else if (mPosition >= mCount) {
            mPosition = 0;
        }
        imageView.setImageResource(mResIdArray[mPosition]);
    }
}

进入动画anim_enter_from_top.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="-100%"
    android:toYDelta="0"
    android:duration="1000" />

退出动画anim_exit_to_bottom.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0"
    android:duration="1000"
    android:toYDelta="100%" />

ViewSwitcher实现切换登陆方式界面案例

手机快捷登录
账号密码登录

登陆界面布局:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".activity.ViewSwitcherActivity">

        <TextView
            android:id="@+id/tv_login_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="50dp"
            android:gravity="center"
            android:paddingBottom="50dp"
            android:text="登陆"
            android:textSize="20sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />


        <ViewSwitcher
            android:id="@+id/vs_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="36dp"
            android:animateFirstView="true"
            android:inAnimation="@anim/slide_in_from_left"
            android:outAnimation="@anim/slide_out_to_left"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@id/tv_login_title">

            <!--手机快捷登录-->
            <include
                android:id="@+id/in_phone_input"
                layout="@layout/login_by_phone_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <!--账号密码登陆-->
            <include
                android:id="@+id/in_phone_pwd_input"
                layout="@layout/login_by_pwd_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </ViewSwitcher>

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/btn_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="登陆"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@id/vs_input" />

        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/tv_switch_login_type"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="账号密码登陆"
            android:textSize="16sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@id/btn_login" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

ViewSwitcherActivity

public class ViewSwitcherActivity extends AppCompatActivity {

    private ActivityViewSwitcherBinding mBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_view_switcher);

        mBinding.tvSwitchLoginType.setOnClickListener(v -> {
            if (mBinding.vsInput.getDisplayedChild() == 0) {
                showPwd();
                mBinding.tvSwitchLoginType.setText("手机快捷登录");
            } else {
                showPhone();
                mBinding.tvSwitchLoginType.setText("账号密码登陆");
            }
        });
    }

    private void showPwd() {
        mBinding.vsInput.setInAnimation(this, R.anim.slide_in_from_right);
        mBinding.vsInput.setOutAnimation(this, R.anim.slide_out_to_left);
        mBinding.vsInput.showNext();

    }

    private void showPhone() {
        mBinding.vsInput.setInAnimation(this, R.anim.slide_in_from_left);
        mBinding.vsInput.setOutAnimation(this, R.anim.slide_out_to_right);
        mBinding.vsInput.showPrevious();
    }
}

slide_in_from_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:duration="250"
        android:fromXDelta="100%p"
        android:toYDelta="0%p" />

</set>

slide_out_to_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="250"
        android:fromXDelta="0.0%p"
        android:toXDelta="100%p" />
</set>

slide_in_from_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="250"
        android:fromXDelta="-100%p"
        android:toXDelta="0.0%p" />
</set>

slide_out_to_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="250"
        android:fromXDelta="0.0%p"
        android:toXDelta="-100%p" />
</set>

ViewFlipper类

ViewFlipper继承ViewAnimator,用于视图的轮播。

  • android:flipInterval指定轮播间隔时间
  • android:autoStart是否自动开始轮播
  • android:inAnimation指定进入时动画
  • android:outAnimation指定退出时动画
       <ViewFlipper
            android:id="@+id/view_flipper"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:autoStart="true"
            android:flipInterval="2000"
            android:inAnimation="@anim/slide_in_from_right"
            android:outAnimation="@anim/slide_out_to_left"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/pic1" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/pic2" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY"
                android:src="@drawable/pic3" />

        </ViewFlipper>

主要方法:
startFlipping()用于手动开始轮播,而stopFlipping()则停止轮播。
showNext()和showPrevious()显示视图的切换。

// 显示上一个视图
private void previous() {
    mViewFlipper.stopFlipping();

    mViewFlipper.setInAnimation(this, R.anim.anim_enter_from_top);
    mViewFlipper.setOutAnimation(this, R.anim.anim_exit_to_bottom);
    mViewFlipper.showPrevious();
}

// 手动开始轮播
private void play() {
    mViewFlipper.setInAnimation(this, R.anim.anim_enter_from_bottom);
    mViewFlipper.setOutAnimation(this, R.anim.anim_exit_to_top);
    mViewFlipper.startFlipping();
}

// 显示下一个视图
private void next() {
    mViewFlipper.stopFlipping();

    mViewFlipper.setInAnimation(this, R.anim.anim_enter_from_bottom);
    mViewFlipper.setOutAnimation(this, R.anim.anim_exit_to_top);
    mViewFlipper.showNext();
}

TextSwitcher和ImageSwitcher

ImageSwitcher和TextSwitcher的继承关系是一样的。两个重要的父类:ViewSwitcher和ViewAnimator。

继承于ViewSwitcher,说明具备了切换功能,

继承于ViewAnimator,说明具备了动画功能。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容