ViewSwither
ViewSwither 继承 ViewAnimator,用来在两个View之间来回切换并可以设置不同的切换动画。ViewSwitcher 只能包含有两个子View,一次性只能显示其中一个。
常用的方法有:
mViewSwitcher1.showPrevious(); // 显示上一个View
mViewSwitcher1.showNext(); // 显示下一个View
- 有三种添加子View的方式:
1.通过XML:
<ViewSwitcher
android:id="@+id/view_switcher_1"
android:layout_width="match_parent"
android:layout_height="180dp">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="24dp"
android:text="ViewSwitcher1#TextView1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="24dp"
android:text="ViewSwitcher1#TextView2"/>
</ViewSwitcher>
2.通过addView添加:
TextView textView = new TextView(this);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(24);
textView.setText("view_switcher_2_" + "textview_" + number);
mViewSwitcher2.addView(textView);
3.通过实现ViewSwitcher.ViewFactory接口中的makeView方法,然后调用ViewSwitcher.setFactory(this)方法:
@Override
public View makeView() {
TextView textView = new TextView(this);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(24);
textView.setText("view_switcher_3_" + "textview");
return textView;
}
// ViewSwitcher.setFactory会通过obtainView来回调makeView方法。
public void setFactory(ViewFactory factory) {
mFactory = factory;
obtainView();
obtainView();
}
- 设置两个View之间的切换动画
ViewSwitcher.setInAnimation // 设置进入动画
ViewSwitcher.setOutAnimation // 设置退出动画
TextSwitcher
TextSwitcher 继承ViewSwitcher,相当于指定了ViewSwitcher的子View只能是TextView。TextSwitcher 可以给屏幕上的Label加上切换动画。通过调用setText(CharSequence)把当前的text退出,显示下一个text并带有动画效果。
- 添加子View的方式跟ViewSwitcher一样,区别就是只能使用TextView。
- 调用setText(CharSequence)来切换Text。
- 切换动画同ViewSwitcher。
public class TextSwitcher1 extends Activity implements ViewSwitcher.ViewFactory {
private int mCounter = 0;
private TextSwitcher mSwitcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_switcher_1);
Animation fadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
Animation fadeOut = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
mSwitcher = (TextSwitcher) findViewById(R.id.text_switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(fadeIn);
mSwitcher.setOutAnimation(fadeOut);
updateCounter();
}
public void onClick(View view) {
mCounter++;
updateCounter();
}
private void updateCounter() {
mSwitcher.setText(String.valueOf(mCounter));
}
@Override
public View makeView() {
// 通过ViewFactory, makeView会被调用两次
TextView textView = new TextView(this);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(36);
return textView;
}
}
ImageSwitcher
ImageSwitcher跟TextSwithcer类似,只是用于两个ImageView之间进行有动画的切换。添加子view(ImageView)的方式和设置切换动画都跟ViewSwitcher一样。当调用ImageSwitcher.setImage*方法时会进行两个ImageView的切换。