xml布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ViewSwitcher
android:id="@+id/switcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inAnimation="@anim/slide_in_top"
android:outAnimation="@anim/slide_out_bottom" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:background="#123456"
android:text="11111111"
android:textSize="32sp" >
</TextView>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:background="#FFFFFFFF"
android:text="22222222"
android:textSize="32sp" >
</TextView>
</RelativeLayout>
</ViewSwitcher>
<Button
android:id="@+id/prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="prev" />
<Button
android:id="@+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="next" />
</LinearLayout>
自定义的动画,也可以用系统自带的,在@android:anim/目录:
slide_in_top.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="2000"
android:fromYDelta="-100%p"
android:toYDelta="0" />
</set>
slide_in_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="2000"
android:fromYDelta="0"
android:toYDelta="100%p" />
</set>
Java代码:
package com.arnold.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ViewSwitcher;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private ViewSwitcher mSwitcher;
private Button btn_prev, btn_next;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSwitcher = (ViewSwitcher) findViewById(R.id.switcher);
mSwitcher.setDisplayedChild(0);
btn_next = (Button) findViewById(R.id.next);
btn_prev = (Button) findViewById(R.id.prev);
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSwitcher.showNext();
}
});
btn_prev.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSwitcher.showPrevious();
}
});
}
}
注意:ViewSwitcher只可以在两种布局中切换,ViewFlipper可以应用多种布局,用法基本一样但后者多出几个方法:
isFlipping:用来判断View切换是否正在进行
setFilpInterval:设置View之间切换的时间间隔
startFlipping:使用上面设置的时间间隔来开始切换所有的View,切换会循环进行
stopFlipping:停止View切换