易采站长站为您分析Android开发之ViewSwitcher用法,结合实例形式分析了ViewSwitcher的功能、使用方法与相关注意事项,需要的朋友可以参考下
本文实例讲述了Android开发之ViewSwitcher用法。,具体如下:
android.widget.ViewSwitcher是ViewAnimator的子类,用于在两个View之间切换,但每次只能显示一个View。
ViewSwitcher的addView函数的代码如下:
/**
* {@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);
}
可以看出,若View的数量超过两个,会抛出异常:java.lang.IllegalStateException,打印 "Can't add more than 2 views to a ViewSwitcher" 。你可以使用ViewSwitcher的factory创建View或添加自己创建的View。
下面用一个例子介绍一下ViewSwitcher的用法。
布局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
xmlns:tools="http://www.easck.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/prev"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="previous" />
<Button
android:id="@+id/next"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="next" />
</LinearLayout>
<ViewSwitcher
android:id="@+id/viewswitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="- Button 2 -" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LinearLayout 2" />
</LinearLayout>
</ViewSwitcher>
</LinearLayout>










