Hiển thị hoặc ẩn chế độ xem bằng ảnh động

Thử cách sử dụng Compose
Jetpack Compose là bộ công cụ giao diện người dùng được đề xuất cho Android. Tìm hiểu cách sử dụng Ảnh động trong Compose.

Trong khi ứng dụng đang được sử dụng, thông tin mới sẽ xuất hiện trên màn hình và thông tin cũ sẽ bị xoá. Việc thay đổi nội dung hiển thị trên màn hình ngay lập tức có thể gây khó chịu và người dùng có thể bỏ lỡ nội dung mới xuất hiện đột ngột. Ảnh động làm chậm quá trình thay đổi và thu hút sự chú ý của người dùng bằng chuyển động để các điểm cập nhật trở nên rõ ràng hơn.

Có 3 ảnh động phổ biến mà bạn có thể sử dụng để hiện hoặc ẩn khung hiển thị: hiển thị ảnh động, ảnh động chuyển đổi và ảnh động lật thẻ.

Tạo ảnh động chuyển cảnh

Ảnh động chuyển tiếp – còn gọi là hiệu ứng làm mờ – dần mờ dần một View hoặc ViewGroup trong khi đồng thời mờ dần trong một ảnh khác. Ảnh động này hữu ích cho các trường hợp bạn muốn chuyển đổi nội dung hoặc chế độ xem trong ứng dụng. Ảnh động chuyển đổi hiển thị ở đây sử dụng ViewPropertyAnimator có sẵn cho Android 3.1 (API cấp 12) trở lên.

Dưới đây là ví dụ về việc chuyển đổi từ chỉ báo tiến trình sang nội dung văn bản:

Hình 1. Ảnh động chuyển tiếp.

Tạo thành phần hiển thị

Tạo hai khung hiển thị mà bạn muốn chuyển đổi. Ví dụ sau đây sẽ tạo một chỉ báo tiến trình và chế độ xem văn bản có thể cuộn:

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

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView style="?android:textAppearanceMedium"
            android:lineSpacingMultiplier="1.2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/lorem_ipsum"
            android:padding="16dp" />

    </ScrollView>

    <ProgressBar android:id="@+id/loading_spinner"
        style="?android:progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

</FrameLayout>

Thiết lập ảnh động chuyển đổi

Để thiết lập ảnh động chuyển đổi, hãy làm như sau:

  1. Tạo biến thành phần cho các chế độ xem mà bạn muốn chuyển đổi. Bạn sẽ cần các tham chiếu này sau này khi sửa đổi khung hiển thị trong ảnh động.
  2. Đặt chế độ hiển thị của khung hiển thị đang được làm mờ thành GONE. Điều này ngăn khung hiển thị sử dụng không gian bố cục và loại bỏ không gian đó khỏi quá trình tính toán bố cục, nhờ đó tăng tốc độ xử lý
  3. Lưu thuộc tính hệ thống config_shortAnimTime vào bộ nhớ đệm trong một biến thành phần. Thuộc tính này xác định thời lượng "ngắn" tiêu chuẩn cho ảnh động. Thời lượng này là lý tưởng cho các ảnh động hoặc ảnh động tinh tế xuất hiện thường xuyên. Bạn cũng có thể sử dụng config_longAnimTimeconfig_mediumAnimTime.

Dưới đây là ví dụ sử dụng bố cục từ đoạn mã trước đó làm khung hiển thị nội dung hoạt động:

Kotlin

class CrossfadeActivity : Activity() {

    private lateinit var contentView: View
    private lateinit var loadingView: View
    private var shortAnimationDuration: Int = 0
    ...
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_crossfade)

        contentView = findViewById(R.id.content)
        loadingView = findViewById(R.id.loading_spinner)

        // Initially hide the content view.
        contentView.visibility = View.GONE

        // Retrieve and cache the system's default "short" animation time.
        shortAnimationDuration = resources.getInteger(android.R.integer.config_shortAnimTime)
    }
    ...
}

Java

public class CrossfadeActivity extends Activity {

    private View contentView;
    private View loadingView;
    private int shortAnimationDuration;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crossfade);

        contentView = findViewById(R.id.content);
        loadingView = findViewById(R.id.loading_spinner);

        // Initially hide the content view.
        contentView.setVisibility(View.GONE);

        // Retrieve and cache the system's default "short" animation time.
        shortAnimationDuration = getResources().getInteger(
                android.R.integer.config_shortAnimTime);
    }
    ...
}

Mờ dần các khung hiển thị

Khi các khung hiển thị đã được thiết lập đúng cách, hãy chuyển đổi giữa các khung hiển thị đó bằng cách thực hiện như sau:

  1. Đối với khung hiển thị mờ dần, hãy đặt giá trị alpha thành 0 và chế độ hiển thị thành VISIBLE theo chế độ cài đặt ban đầu là GONE. Thao tác này giúp chế độ xem có thể nhìn thấy được nhưng trong suốt.
  2. Đối với khung hiển thị mờ dần, hãy tạo ảnh động giá trị alpha từ 0 đến 1. Đối với khung hiển thị mờ dần, hãy tạo ảnh động cho giá trị alpha từ 1 thành 0.
  3. Sử dụng onAnimationEnd() trong Animator.AnimatorListener, đặt chế độ hiển thị của khung hiển thị đang mờ dần thành GONE. Mặc dù giá trị alpha là 0, nhưng việc đặt chế độ hiển thị của khung hiển thị thành GONE sẽ ngăn khung hiển thị sử dụng không gian bố cục và loại bỏ không gian này khỏi các tính toán bố cục, giúp tăng tốc độ xử lý.

Phương thức sau đây cho thấy ví dụ về cách thực hiện việc này:

Kotlin

class CrossfadeActivity : Activity() {

    private lateinit var contentView: View
    private lateinit var loadingView: View
    private var shortAnimationDuration: Int = 0
    ...
    private fun crossfade() {
        contentView.apply {
            // Set the content view to 0% opacity but visible, so that it is
            // visible but fully transparent during the animation.
            alpha = 0f
            visibility = View.VISIBLE

            // Animate the content view to 100% opacity and clear any animation
            // listener set on the view.
            animate()
                    .alpha(1f)
                    .setDuration(shortAnimationDuration.toLong())
                    .setListener(null)
        }
        // Animate the loading view to 0% opacity. After the animation ends,
        // set its visibility to GONE as an optimization step so it doesn't
        // participate in layout passes.
        loadingView.animate()
                .alpha(0f)
                .setDuration(shortAnimationDuration.toLong())
                .setListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        loadingView.visibility = View.GONE
                    }
                })
    }
}

Java

public class CrossfadeActivity extends Activity {

    private View contentView;
    private View loadingView;
    private int shortAnimationDuration;
    ...
    private void crossfade() {

        // Set the content view to 0% opacity but visible, so that it is
        // visible but fully transparent during the animation.
        contentView.setAlpha(0f);
        contentView.setVisibility(View.VISIBLE);

        // Animate the content view to 100% opacity and clear any animation
        // listener set on the view.
        contentView.animate()
                .alpha(1f)
                .setDuration(shortAnimationDuration)
                .setListener(null);

        // Animate the loading view to 0% opacity. After the animation ends,
        // set its visibility to GONE as an optimization step so it doesn't
        // participate in layout passes.
        loadingView.animate()
                .alpha(0f)
                .setDuration(shortAnimationDuration)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        loadingView.setVisibility(View.GONE);
                    }
                });
    }
}

Tạo ảnh động lật thẻ

Lật thẻ để chuyển đổi giữa các khung hiển thị nội dung bằng cách hiển thị một ảnh động mô phỏng thẻ lật. Ảnh động lật thẻ xuất hiện ở đây sử dụng FragmentTransaction.

Sau đây là ví dụ minh hoạ tính năng lật thẻ:

Hình 2. Ảnh động lật thẻ.

Tạo đối tượng trình tạo ảnh động

Để tạo ảnh động lật thẻ, bạn cần 4 ảnh động. Hai ảnh động dùng khi mặt trước của thẻ tạo hiệu ứng động, sang trái và vào bên trong và từ bên trái. Hai ảnh động còn lại là khi mặt sau của thẻ tạo hiệu ứng động từ bên phải và khi thẻ chuyển động ra và sang phải.

card_flip_left_in.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Before rotating, immediately set the alpha to 0. -->
    <objectAnimator
        android:valueFrom="1.0"
        android:valueTo="0.0"
        android:propertyName="alpha"
        android:duration="0" />

    <!-- Rotate. -->
    <objectAnimator
        android:valueFrom="-180"
        android:valueTo="0"
        android:propertyName="rotationY"
        android:interpolator="@android:interpolator/accelerate_decelerate"
        android:duration="@integer/card_flip_time_full" />

    <!-- Halfway through the rotation, set the alpha to 1. See startOffset. -->
    <objectAnimator
        android:valueFrom="0.0"
        android:valueTo="1.0"
        android:propertyName="alpha"
        android:startOffset="@integer/card_flip_time_half"
        android:duration="1" />
</set>

card_flip_left_out.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Rotate. -->
    <objectAnimator
        android:valueFrom="0"
        android:valueTo="180"
        android:propertyName="rotationY"
        android:interpolator="@android:interpolator/accelerate_decelerate"
        android:duration="@integer/card_flip_time_full" />

    <!-- Halfway through the rotation, set the alpha to 0. See startOffset. -->
    <objectAnimator
        android:valueFrom="1.0"
        android:valueTo="0.0"
        android:propertyName="alpha"
        android:startOffset="@integer/card_flip_time_half"
        android:duration="1" />
</set>

card_flip_right_in.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Before rotating, immediately set the alpha to 0. -->
    <objectAnimator
        android:valueFrom="1.0"
        android:valueTo="0.0"
        android:propertyName="alpha"
        android:duration="0" />

    <!-- Rotate. -->
    <objectAnimator
        android:valueFrom="180"
        android:valueTo="0"
        android:propertyName="rotationY"
        android:interpolator="@android:interpolator/accelerate_decelerate"
        android:duration="@integer/card_flip_time_full" />

    <!-- Halfway through the rotation, set the alpha to 1. See startOffset. -->
    <objectAnimator
        android:valueFrom="0.0"
        android:valueTo="1.0"
        android:propertyName="alpha"
        android:startOffset="@integer/card_flip_time_half"
        android:duration="1" />
</set>

card_flip_right_out.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Rotate. -->
    <objectAnimator
        android:valueFrom="0"
        android:valueTo="-180"
        android:propertyName="rotationY"
        android:interpolator="@android:interpolator/accelerate_decelerate"
        android:duration="@integer/card_flip_time_full" />

    <!-- Halfway through the rotation, set the alpha to 0. See startOffset. -->
    <objectAnimator
        android:valueFrom="1.0"
        android:valueTo="0.0"
        android:propertyName="alpha"
        android:startOffset="@integer/card_flip_time_half"
        android:duration="1" />
</set>

Tạo thành phần hiển thị

Mỗi bên của thẻ là một bố cục riêng biệt có thể chứa bất kỳ nội dung nào bạn muốn, chẳng hạn như 2 thành phần hiển thị văn bản, 2 hình ảnh hoặc bất kỳ tổ hợp thành phần hiển thị nào để lật. Sử dụng 2 bố cục này trong các mảnh mà bạn tạo ảnh động sau này. Bố cục sau đây sẽ tạo một mặt của thẻ, trong đó hiển thị văn bản:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#a6c"
    android:padding="16dp"
    android:gravity="bottom">

    <TextView android:id="@android:id/text1"
        style="?android:textAppearanceLarge"
        android:textStyle="bold"
        android:textColor="#fff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/card_back_title" />

    <TextView style="?android:textAppearanceSmall"
        android:textAllCaps="true"
        android:textColor="#80ffffff"
        android:textStyle="bold"
        android:lineSpacingMultiplier="1.2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/card_back_description" />

</LinearLayout>

Và bố cục tiếp theo sẽ tạo phần còn lại của thẻ, hiển thị ImageView:

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/image1"
    android:scaleType="centerCrop"
    android:contentDescription="@string/description_image_1" />

Tạo mảnh

Tạo các lớp mảnh cho mặt trước và mặt sau của thẻ. Trong các lớp mảnh, hãy trả về bố cục mà bạn đã tạo từ phương thức onCreateView(). Sau đó, bạn có thể tạo các thực thể của mảnh này trong hoạt động gốc mà bạn muốn hiển thị thẻ.

Ví dụ sau đây cho thấy các lớp mảnh lồng nhau bên trong hoạt động gốc sử dụng các lớp này:

Kotlin

class CardFlipActivity : FragmentActivity() {
    ...
    /**

                    *   A fragment representing the front of the card.
     */
    class CardFrontFragment : Fragment() {

    override fun onCreateView(
                inflater: LayoutInflater,
                container: ViewGroup?,
                savedInstanceState: Bundle?
    ): View = inflater.inflate(R.layout.fragment_card_front, container, false)
    }

    /**
    *   A fragment representing the back of the card.
    */
    class CardBackFragment : Fragment() {

    override fun onCreateView(
                inflater: LayoutInflater,
                container: ViewGroup?,
                savedInstanceState: Bundle?
    ): View = inflater.inflate(R.layout.fragment_card_back, container, false)
    }
}

Java

public class CardFlipActivity extends FragmentActivity {
    ...
    /**
    *   A fragment representing the front of the card.
    */
    public class CardFrontFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_card_front, container, false);
    }
    }

    /**
    *   A fragment representing the back of the card.
    */
    public class CardBackFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_card_back, container, false);
    }
    }
}

Tạo hiệu ứng cho thao tác lật thẻ

Hiển thị các mảnh bên trong một hoạt động mẹ. Để làm điều này, hãy tạo bố cục cho hoạt động của bạn. Ví dụ sau đây sẽ tạo một FrameLayout mà bạn có thể thêm các mảnh vào trong thời gian chạy:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Trong mã hoạt động, hãy đặt thành phần hiển thị nội dung thành bố cục mà bạn tạo. Bạn nên hiển thị một mảnh mặc định khi hoạt động được tạo. Hoạt động mẫu sau đây minh hoạ cách hiển thị mặt trước của thẻ theo mặc định:

Kotlin

class CardFlipActivity : FragmentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_activity_card_flip)
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                    .add(R.id.container, CardFrontFragment())
                    .commit()
        }
    }
    ...
}

Java

public class CardFlipActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity_card_flip);

        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.container, new CardFrontFragment())
                    .commit();
        }
    }
    ...
}

Khi mặt trước của thẻ xuất hiện, bạn có thể hiện mặt sau của thẻ bằng ảnh động lật tại một thời điểm thích hợp. Tạo một phương thức để hiển thị mặt còn lại của thẻ nhằm thực hiện những việc sau:

  • Đặt ảnh động tuỳ chỉnh mà bạn đã tạo cho các hiệu ứng chuyển đổi mảnh.
  • Thay thế mảnh hiển thị bằng một mảnh mới và tạo ảnh động cho sự kiện này bằng ảnh động tuỳ chỉnh mà bạn đã tạo.
  • Thêm mảnh đã hiển thị trước đó vào ngăn xếp lui của mảnh để khi người dùng nhấn vào nút Quay lại, thẻ sẽ lật trở lại.

Kotlin

class CardFlipActivity : FragmentActivity() {
    ...
    private fun flipCard() {
        if (showingBack) {
            supportFragmentManager.popBackStack()
            return
        }

        // Flip to the back.

        showingBack = true

        // Create and commit a new fragment transaction that adds the fragment
        // for the back of the card, uses custom animations, and is part of the
        // fragment manager's back stack.

        supportFragmentManager.beginTransaction()

                // Replace the default fragment animations with animator
                // resources representing rotations when switching to the back
                // of the card, as well as animator resources representing
                // rotations when flipping back to the front, such as when the
                // system Back button is tapped.
                .setCustomAnimations(
                        R.animator.card_flip_right_in,
                        R.animator.card_flip_right_out,
                        R.animator.card_flip_left_in,
                        R.animator.card_flip_left_out
                )

                // Replace any fragments in the container view with a fragment
                // representing the next page, indicated by the just-incremented
                // currentPage variable.
                .replace(R.id.container, CardBackFragment())

                // Add this transaction to the back stack, letting users press
                // the Back button to get to the front of the card.
                .addToBackStack(null)

                // Commit the transaction.
                .commit()
    }
}

Java

public class CardFlipActivity extends FragmentActivity {
    ...
    private void flipCard() {
        if (showingBack) {
            getSupportFragmentManager().popBackStack();
            return;
        }

        // Flip to the back.

        showingBack = true;

        // Create and commit a new fragment transaction that adds the fragment
        // for the back of the card, uses custom animations, and is part of the
        // fragment manager's back stack.

        getSupportFragmentManager()
                .beginTransaction()

                // Replace the default fragment animations with animator
                // resources representing rotations when switching to the back
                // of the card, as well as animator resources representing
                // rotations when flipping back to the front, such as when the
                // system Back button is pressed.
                .setCustomAnimations(
                        R.animator.card_flip_right_in,
                        R.animator.card_flip_right_out,
                        R.animator.card_flip_left_in,
                        R.animator.card_flip_left_out)

                // Replace any fragments in the container view with a fragment
                // representing the next page, indicated by the just-incremented
                // currentPage variable.
                .replace(R.id.container, new CardBackFragment())

                // Add this transaction to the back stack, letting users press
                // Back to get to the front of the card.
                .addToBackStack(null)

                // Commit the transaction.
                .commit();
    }
}

Tạo ảnh động hiển thị vòng tròn

Ảnh động hiển thị giúp người dùng tiếp tục sử dụng được hình ảnh khi bạn hiện hoặc ẩn một nhóm thành phần trên giao diện người dùng. Phương thức ViewAnimationUtils.createCircularReveal() cho phép bạn tạo ảnh động cho một vòng tròn cắt để hiển thị hoặc ẩn khung hiển thị. Ảnh động này được cung cấp trong lớp ViewAnimationUtils, có sẵn cho Android 5.0 (API cấp 21) trở lên.

Dưới đây là ví dụ cho thấy cách hiển thị một khung hiển thị đã ẩn trước đó:

Kotlin

// A previously invisible view.
val myView: View = findViewById(R.id.my_view)

// Check whether the runtime version is at least Android 5.0.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Get the center for the clipping circle.
    val cx = myView.width / 2
    val cy = myView.height / 2

    // Get the final radius for the clipping circle.
    val finalRadius = Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()

    // Create the animator for this view. The start radius is 0.
    val anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0f, finalRadius)
    // Make the view visible and start the animation.
    myView.visibility = View.VISIBLE
    anim.start()
} else {
    // Set the view to invisible without a circular reveal animation below
    // Android 5.0.
    myView.visibility = View.INVISIBLE
}

Java

// A previously invisible view.
View myView = findViewById(R.id.my_view);

// Check whether the runtime version is at least Android 5.0.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Get the center for the clipping circle.
    int cx = myView.getWidth() / 2;
    int cy = myView.getHeight() / 2;

    // Get the final radius for the clipping circle.
    float finalRadius = (float) Math.hypot(cx, cy);

    // Create the animator for this view. The start radius is 0.
    Animator anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0f, finalRadius);

    // Make the view visible and start the animation.
    myView.setVisibility(View.VISIBLE);
    anim.start();
} else {
    // Set the view to invisible without a circular reveal animation below
    // Android 5.0.
    myView.setVisibility(View.INVISIBLE);
}

Ảnh động ViewAnimationUtils.createCircularReveal() có 5 tham số. Thông số đầu tiên là thành phần hiển thị mà bạn muốn ẩn hoặc hiện trên màn hình. Hai tham số tiếp theo là toạ độ X và Y cho tâm của vòng tròn cắt. Thông thường, đây là trung tâm của khung hiển thị, nhưng bạn cũng có thể sử dụng điểm mà người dùng nhấn vào để ảnh động bắt đầu tại nơi họ chọn. Tham số thứ tư là bán kính bắt đầu của vòng tròn cắt.

Trong ví dụ trước, bán kính ban đầu được đặt thành 0 để vòng tròn ẩn thành phần hiển thị đang hiển thị. Tham số cuối cùng là bán kính cuối cùng của vòng tròn. Khi hiển thị một khung hiển thị, hãy tăng bán kính cuối cùng lớn hơn khung hiển thị đó để khung hiển thị đó có thể hiển thị đầy đủ trước khi ảnh động kết thúc.

Để ẩn một khung hiển thị đã hiển thị trước đó, hãy làm như sau:

Kotlin

// A previously visible view.
val myView: View = findViewById(R.id.my_view)

// Check whether the runtime version is at least Android 5.0.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Get the center for the clipping circle.
    val cx = myView.width / 2
    val cy = myView.height / 2

    // Get the initial radius for the clipping circle.
    val initialRadius = Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()

    // Create the animation. The final radius is 0.
    val anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, initialRadius, 0f)

    // Make the view invisible when the animation is done.
    anim.addListener(object : AnimatorListenerAdapter() {

        override fun onAnimationEnd(animation: Animator) {
            super.onAnimationEnd(animation)
            myView.visibility = View.INVISIBLE
        }
    })

    // Start the animation.
    anim.start()
} else {
    // Set the view to visible without a circular reveal animation below
    // Android 5.0.
    myView.visibility = View.VISIBLE
}

Java

// A previously visible view.
final View myView = findViewById(R.id.my_view);

// Check whether the runtime version is at least Android 5.0.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Get the center for the clipping circle.
    int cx = myView.getWidth() / 2;
    int cy = myView.getHeight() / 2;

    // Get the initial radius for the clipping circle.
    float initialRadius = (float) Math.hypot(cx, cy);

    // Create the animation. The final radius is 0.
    Animator anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, initialRadius, 0f);

    // Make the view invisible when the animation is done.
    anim.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            myView.setVisibility(View.INVISIBLE);
        }
    });

    // Start the animation.
    anim.start();
} else {
    // Set the view to visible without a circular reveal animation below Android
    // 5.0.
    myView.setVisibility(View.VISIBLE);
}

Trong trường hợp này, bán kính ban đầu của vòng tròn cắt được đặt lớn bằng khung hiển thị để có thể nhìn thấy khung hiển thị trước khi ảnh động bắt đầu. Bán kính cuối cùng được đặt thành 0 để chế độ xem sẽ bị ẩn khi ảnh động kết thúc. Thêm trình nghe vào ảnh động để có thể đặt chế độ hiển thị của khung hiển thị thành INVISIBLE khi ảnh động hoàn tất.

Tài nguyên khác