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

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

Шкодим

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

TextSwitcher

Компонент TextSwitcher находится в разделе Transitions и предназначен для анимированной смены текста.

Если использовать обычный TextView и выводить в нём новые сообщения, то текст будет выводиться мгновенно - предыдущий текст исчезает, а новый появляется вместо него. Но, если вам нужно сделать красиво, то TextSwitcher поможет вам.

Общий принцип использования следующий - с помощью интерфейса ViewFactory и его метода makeView() создаются дочерние элементы TextView, которые переключаются между собой с анимацией. В методе setFactory() указываем реализованный интерфейс. В завершение указываем два типа анимации в метода setInAnimation() и setOutAnimation().

Разместим на форме кнопку и TextSwitcher:


<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/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="OnClick"
        android:text="Начать счёт" />

    <TextSwitcher
        android:id="@+id/textSwitcher"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

Теперь переходим к коду:


package ru.alexanderklimov.testapplication;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextSwitcher;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity implements TextSwitcher.ViewFactory {

    private TextSwitcher mTextSwitcher;
    private int mCounter = 0;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mTextSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher);
        mTextSwitcher.setFactory(this);

        Animation inAnimation = AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in);
        Animation outAnimation = AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out);
        mTextSwitcher.setInAnimation(inAnimation);
        mTextSwitcher.setOutAnimation(outAnimation);

        updateCounter();
    }

    public void onClick(View v) {
        mCounter++;
        updateCounter();
    }

    private void updateCounter() {
        mTextSwitcher.setText(String.valueOf(mCounter));
    }

    @Override
    public View makeView() {
        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL);
        textView.setTextSize(70);
        textView.setTextColor(Color.RED);
        return textView;
    }
}

Данный пример немного похож на пример подсчета ворон, только на этот раз результаты выводим не в текстовом поле, а в TextSwitcher. На скриншоте этого не увидеть, поэтому нужно попробовать пример на эмуляторе или устройстве. Если приглядеться, то можно увидеть у цифры 6 проступающую следующую цифру 7.

TextSwitcher

На что обратить внимание - мы используем системные анимации android.R.anim.fade_in и android.R.anim.fade_out. Поэтому нам не нужно создавать файлы XML для анимации и сохранять их в res/anim, как мы это делали в некоторых уроках. Метод setFactory позволяет указать нужный класс. Метод makeView() должен возвращать элемент View подходящего типа, в нашем случае TextView. Заметьте, что в методе мы формируем своеобразный шаблон (размер, цвет, позиция) для TextView, а вывод содержимого формируется в других методах.

Слайд-шоу

Рассмотрим теперь пример с другой анимацией в виде слайд-шоу. Разметку оставим из предыдущего примера - кнопку и TextSwitcher

Принцип тот же. Только заменяем анимацию затемнения на анимацию слайд-шоу.


// Если этот код работает, его написал Александр Климов,
// а если нет, то не знаю, кто его писал.

package ru.alexanderklimov.testapplication;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;


public class MainActivity extends ActionBarActivity {

    private TextSwitcher mTextSwitcher;
    private String[] mWordsArray = {"А", "у нас", "сегодня",
            "кошка", "родила", "вчера", "котят"};
    int mCurrentIndex;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

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

        mTextSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher);
        mTextSwitcher.setInAnimation(slideInLeftAnimation);
        mTextSwitcher.setOutAnimation(slideOutRightAnimation);

        mTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                TextView textView = new TextView(MainActivity.this);
                textView.setTextSize(30);
                textView.setTextColor(Color.RED);
                textView.setGravity(Gravity.CENTER_HORIZONTAL);
                textView.setTypeface(Typeface.DEFAULT_BOLD);
                textView.setShadowLayer(10, 10, 10, Color.BLACK);
                return textView;
            }
        });

        mCurrentIndex = 0;
        mTextSwitcher.setText(mWordsArray[mCurrentIndex]);
    }

    public void onClick(View v) {
        if (mCurrentIndex == mWordsArray.length - 1) {
            mCurrentIndex = 0;
            mTextSwitcher.setText(mWordsArray[mCurrentIndex]);
        } else {
            mTextSwitcher.setText(mWordsArray[++mCurrentIndex]);
        }
    }
}


Реклама