Освой программирование играючи

Сайт Александра Климова

Шкодим

/* Моя кошка замечательно разбирается в программировании. Стоит мне объяснить проблему ей - и все становится ясно. */
John Robbins, Debugging Applications, Microsoft Press, 2000

ViewSwitcher

Компонент ViewSwitcher может работать только с двумя дочерними элементами, тогда как ViewFlipper может использовать несколько компонентов. Поэтому присутствие данного элемента в панели инструментов выглядит немного странным. Тем более, что ещё есть ViewAnimator, который также обладает необходимыми возможностями. При попытке вложить более двух дочерних элементов вы получите сообщение об ошибке.

Находится в разделе Transitions.

Рассмотрим самый простой пример.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ViewSwitcher
        android:id="@+id/viewSwitcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/cat10" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/cat21" />
    </ViewSwitcher>

</RelativeLayout>

Переключение между двумя ImageView сделаем с помощью анимации затемнения:


ViewSwitcher viewSwitcher;

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

	setContentView(R.layout.activity_main);

	viewSwitcher = findViewById(R.id.viewSwitcher);
	Animation inAnim = new AlphaAnimation(0, 1);
	inAnim.setDuration(2000);
	Animation outAnim = new AlphaAnimation(1, 0);
	outAnim.setDuration(2000);

	viewSwitcher.setInAnimation(inAnim);
	viewSwitcher.setOutAnimation(outAnim);

	viewSwitcher.setOnClickListener(new View.OnClickListener() {
		public void onClick(View v) {
			viewSwitcher.showNext();
		}
	});
}

Обратите внимание, что для переключения используется метод ViewAnimator.showNext(). Так как ViewSwitcher наследуется от ViewAnimator, то мы можем использовать метод класса-родителя. Чтобы переключиться на следующую картинку, достаточно простого касания экрана.

Дочерним элементом может быть и контейнер, в который можно вложить несколько компонентов. Рассмотрим вариант с анимацией слайд-шоу.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/butNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="onClick"
        android:text="Далее" />

    <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:layout_gravity="center"
            android:gravity="center"
            android:src="@drawable/ic_android_cat" />

        <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="А я кнопка" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="А я тогда кто?" />
        </LinearLayout>
    </ViewSwitcher>

</LinearLayout>

И код для листания. Кстати, хочу обратить ваше внимание, что кроме метода showNext() есть ещё метод showPrevious() для перехода в другую сторону.


package ru.alexanderklimov.switcher;

import android.app.Activity;

import android.os.Bundle;

import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ViewSwitcher;

public class MainActivity extends Activity {

	ViewSwitcher viewSwitcher;
	Animation slide_in_left, slide_out_right;

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

		setContentView(R.layout.activity_main);

		viewSwitcher = findViewById(R.id.viewSwitcher);

		slide_in_left = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_in_left);
		slide_out_right = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_out_right);

		viewSwitcher.setInAnimation(slide_in_left);
		viewSwitcher.setOutAnimation(slide_out_right);
	}

	public void onClick(View view) {
		viewSwitcher.showNext();
	}
}
Реклама