Lập trình Android - ViewAnimator

ViewAnimator trong Android

ViewAnimator  là lớp con của lớp FrameLayout thường được sử dụng để chuyển đổi (lật) giữa các view. ViewAnimator  rất hữu ích giúp ta chuy6e3n đổi giữa các view với nhau. 

ViewAnimator là lớp cha của các lớp ViewFlipper, ViewSwitcher và các view khác. Nó được sử dụng để chuyển đổi giữa các view khác nhau.


ViewAnimator code trong XML:

<ViewAnimator
android:id="@+id/simpleViewAnimator"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<!--   Add View’s Here -->

</ViewAnimator>

Các bước tạo ViewAnimator

Bước 1: Khởi tạo ViewFlipper bằng phương thức findViewById(), hoặc bạn có thể tạo động .
Bước 2: Thiết lập view để hiển thị ảnh bằng phương thức switcherid.setFactory()
Bước 3: Thiết lập ảnh động dạng đưa vào dần dùng phương thức switcherid.setInAnimation()
Bước 4: Thiết lập ảnh động dạng làm mờ dần dùng phương thức switcherid.setOutAnimation()


Các phương thức quan trọng của ViewAnimator
1. showNext(): Phương thức này được sử dụng để hiển thị view kế tiếp trong ViewAnimator
Ví dụ sau chúng ta thiết lập sự kiện cho button để gọi phương thức showNext() để hiển thị view kế tiếp trong ViewAnimator

ViewAnimator simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); //get the reference of ViewAnimator

Button btnNext=(Button) findViewById(R.id.buttonNext); //get the reference of Button
// set Click event on next button
btnNext.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
// show the next view of ViewAnimator
simpleViewAnimator.showNext();
}
});

2. showPrevious():  Phương thức này được sử dụng để hiển thị view trước trong ViewAnimator.
Ví dụ sau chúng ta thiết lập sự kiện cho button để gọi phương thức showPrevious() để hiển thị view trước trong ViewAnimator

ViewAnimator simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator

Button btnPrevious=(Button) findViewById(R.id.buttonPrevious); // get the reference of Button
// set Click event on next button
btnPrevious.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
// show the next view of ViewFlipper
simpleViewAnimator.showPrevious();
}
});


 

3. loadAnimation(Context context, int id): Phương thức này được sử dụng khi chúng ta cần tạo ra một đối tượng view động.
Ví dụ sau chúng ta tạo ra một đối tượng lớp Animation và nạp một view động bằng cách sử dụng lớp AnimationUtils

// Load Animation using AnimationUtils class
 Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
 Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);

4. setInAnimation(Animation inAnimation): Phương thức này thường được sử dụng để thiết lập một view động xuất hiện ở giữa màn hình.
Ví dụ sau chúng ta tạo ra một đối tượng lớp Animation và nạp một view động bằng cách sử dụng lớp AnimationUtils, sau đó thiết lập Animation lên ViewAnimator.

ViewAnimator simpleViewAnimator=(ViewAnimator)findViewById(R.id.simpleViewAnimator); // initiate a ViewAnimator
Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left); // load an animation
simpleViewAnimator.setInAnimation(in); // set in Animation for ViewAnimator

5. setOutAnimation(Animation outAnimation): Phương thức đối ngược với phương thức setInAnimation().
Ví dụ sau chúng ta tạo ra một đối tượng lớp Animation và nạp một view động bằng cách sử dụng lớp AnimationUtils, sau đó thiết lập view mờ dần lên ViewAnimator.

ViewAnimator simpleViewAnimator=(ViewAnimator)findViewById(R.id. simpleViewAnimator); // get reference of ViewAnimator
Animation out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right); // load an animation
simpleViewAnimator.setOutAnimation(out); // set out Animation for ViewAnimator

6. addView(View child):  Phương thức này được sử dụng để thêm một view tại thời điểm chạy trong ViewAnimator.
Ví dụ sau chúng ta tạo một view mới TextView rồi sau đó thêm nó vào ViewAnimator

ViewAnimator simpleViewAnimator=(ViewAnimator)findViewById(R.id.simpleViewAnimator); // get reference of ViewAnimator

TextView textView = new TextView(this); // create a TextView
textView.setText("View Animator TextView"); // set text in TextView
simpleViewAnimator.addView(textView); // add the TextView in ViewAnimator

7. getCurrentView(): Phương thức này được sử dụng để lấy view đang hiển thị.
Ví dụ sau chúng ta lấy view đang hiển thị

ViewAnimator simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator
View view = simpleViewAnimator.getCurrentView(); // get current displayed child view of ViewAnimator

8. getDisplayedChild(): Phương thức này được sử dụng để lấy chỉ mục (index) của view đang hiển thị. Phương thức này trả về giá trị là số nguyên là chỉ mục của view.
Ví dụ sau chúng ta lấy chỉ mục của view đang hiển thị

ViewAnimator simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator
int  displayedChildIndex = simpleViewAnimator.getDisplayedChild(); // get index for current displayed child view of ViewAnimator

9. removeAllViews(): Phương thức này được sử dụng để xóa tất cả các view trong ViewGroup.

Ví dụ sau chúng ta xóa tất cả các view trong ViewGroup.

ViewAnimator simpleViewAnimator=(ViewAnimator)findViewById(R.id. simpleViewAnimator); // get reference of ViewAnimator

simpleViewAnimator.removeAllViews(); // remove all the child views of ViewAnimator

10. removeView(View view): Phương thức này được sử dụng để xóa một view của ViewAnimator. Trong phương thức này đối tượng truyền vào là view cần xóa.

Ví dụ sau chúng ta lấy một view đang hiển thị và sau đó xóa nó

ViewAnimator simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator
View view=simpleViewAnimator.getCurrentView(); // get current displayed child view of ViewAnimator
simpleViewAnimator.removeView(view); // remove the current displayed child view of ViewAnimator

11. removeViewAt(int index): Phương thức này được sử dụng để xóa vị trí trong group. Ví phương thức này chúng ta cần truyền vị trí để xóa.

Ví sau trước tiên chúng ta lấy vị trí của view và sau đó xóa view này dựa vào vị trí 

ViewAnimator simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator
int  displayedChildIndex = simpleViewAnimator.getDisplayedChild(); // get index for current displayed child view of ViewAnimator
simpleViewAnimator.removeViewAt(displayedChildIndex); // remove the current displayed child view of ViewAnimator

12. setDisplayedChild(int whichChild):  Phương thức này được sử dụng để thiết lập một view sẽ được hiển thị trong ViewAnimator. Trong phương chúng ta cần thiết lập vị trí của view sẽ được hiển thị trong ViewAnimator.

ViewAnimator simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator
simpleViewAnimator.setDisplayedChild(1); // set the indez of current displayed child view of ViewAnimator

13. setAnimateFirstView(boolean animate): Phương thức này được sử dụng để chỉ ra trong các view chúng ta muốn view nào được hiển thị đầu tiên, khi ViewAnimator được hiển thị. Trong phương thức này chỉ truyền 2 giá trị true hoặc false.

Ví dụ sau chúng ta thiết lập giá trị true cho phương thức setAnimateFirstView()

ViewAnimator simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator
simpleViewAnimator.setAnimateFirstView(true); // set true value for setAnimateFirstView

Trong code trên view sẽ chuyển hoạt trong ViewAnimator. Nếu thay nó bằng false sẽ không chuyển hoạt.

14. getAnimateFirstView(): Phương thức này được sử dụng để kiểm tra view hiện tại được chuyển hoạt lần đâu trong ViewAnimator khi được hiển thị. Phương thức này trả về giá trị true hoặc false.

Ví dụ sau trước tiên chúng ta thiết lập giá trị true cho phương thức setAnimateFirstView, sau đó kiểm tra view hiện tại được chuyển hoạt lần đâu trong ViewAnimator khi được hiển thị hay không

ViewAnimator simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator
simpleViewAnimator.setAnimateFirstView(true); // set true value for setAnimateFirstView
Boolean isAnimateFirstTime=simpleViewAnimator.getAnimateFirstView(); // checks whether the view should animate first time or not.

Một số thuộc tính thường dùng của ViewAnimator

1. android:id: Là thuộc tính duy nhất của ViewAnimator.

< ViewAnimator

android:id="@+id/simpleViewAnimator"
android:layout_width="match_parent"
android:layout_height="wrap_content" >  <!-- id of the ViewAnimator used to uniquely identify it -->
<!--   Add View’s Here -- >

</ ViewAnimator >

Dựa vào Id ta sẽ lấy được control theo đúng Id này, xem code bên dưới để biết cách lấy control theo Id

ViewAnimator simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator

2. android:animateFirstView: Thuộc tính này được sử dụng để chỉ ra trong các view chúng ta muốn view nào được hiển thị đầu tiên, khi ViewAnimator được hiển thị. Trong thuộc tính này chỉ thiết lập 2 giá trị true hoặc false.

Ví dụ sau chúng ta thiết lập giá trị true cho thuộc tính animateFirstView

<ViewAnimator
android:id="@+id/simpleViewAnimator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateFirstView="true"> <!--set true value for animateFirstView attribute -->

<!--   Add View’s Here -- >

</ ViewAnimator >

3. android:inAnimation: Thuộc tính này được sử dụng để chỉ ra hướng chuyển hoạt khi view được hiển thị.

Ví dụ sau chúng ta thiết lập hướng chuyển hoạt từ bên trái cho thuộc tính inAnimation

<ViewAnimator
android:id="@+id/simpleViewAnimator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateFirstView="true"
android:inAnimation="@android:anim/slide_in_left"> <!-- slide in left animation for the child views of ViewAnimator-->

<!--   Add View’s Here -- >

</ ViewAnimator >

4. android:outAnimation: Thuộc tính này được sử dụng để chỉ ra hướng chuyển hoạt khi view được dấu.

Ví dụ sau chúng ta thiết lập hướng chuyển hoạt từ bên phải cho thuộc tính outAnimation

<ViewAnimator
android:id="@+id/simpleViewAnimator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateFirstView="true"
android:outAnimation="@android:anim/slide_out_right"> <!-- slide out right animation for the child views of ViewAnimator-->

<!--Add View’s Here-->

</ViewAnimator>

5. android:padding: Thuộc tính này xác định khoảng cách từ đường viền của ViewAnimation với nội dung nó chứa: left, right, top or bottom. Cũng ví dụ trên bây giờ chúng ta xác định padding=10dp từ mọi phía cho.

<ViewAnimator
android:id="@+id/simpleViewAnimator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"> <!-- set 10 dp padding from all the sides of ViewAnimator -->

<!-- Add View’s Here-->

</ViewAnimator>

5. android:background: Thuộc tính này thiết lập màu nền ViewAnimation 

Code sau chúng ta thiết lập màu nền, màu đỏ cho ViewAnimation 

<ViewAnimator
android:id="@+id/simpleViewAnimator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#f00"> <!-- set red color in the background of ViewFlipper -->

<!--   Add View’s Here -- >

</ViewAnimator >

Thiết lập màu nền trong java class

ViewAnimator simpleViewAnimator=(ViewAnimator)findViewById(R.id. simpleViewAnimator); // get reference of ViewAnimator
simpleViewAnimator.setBackgroundColor(Color.RED);// set red color in the background of ViewAnimator

Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có một ViewAnimator, một Button.Thiết lập sự kiện cho Button, khi người sử dụng click vào Button sẽ chuyển qua hình khác. Tiến hành tạo project, vào thư mục  res /layout -> activity_main.xml thiết kế giao diện sau:

Bước 1: Tạo một project tên là ImageSwitcherFile->New->Android Application Project điền các thông tin ->Next ->Finish

Bước 2: Mở res -> layout -> xml (hoặc) activity_main.xml và thêm code, chúng ta sẽ tạo các đối tượng ViewAnimator và Button trong Linear Layout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical">

    <ViewAnimator
        android:id="@+id/simpleViewAnimator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ViewAnimator>


    <Button
        android:id="@+id/buttonNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="150dp"
        android:background="#055"
        android:text="NEXT"
        android:textColor="#fff"
        android:textStyle="bold" />

</LinearLayout>

Bước 3: Mở app -> src ->MainActivity.java

Trong bước này chúng ta khởi tạo ViewAnimation Button. Chúng ta cũng khai báo một mảng để chứa các id của image, đồng thời thêm 5 ImageView vào ViewAnimation bằng phương thức addView(). Chúng ta cũng sử dụng một Button để lật qua lại giữa các view trong ViewAnimation

 Và ở đây chúng ta cũng load và thiết lập các thanh trượt bên trái và bên phải cùa hình động.  Khi người sử dụng click vào button "NEXTViewAnimation sẽ chuyển từ image hiện tại sang image kế tiếp. Chúng ta tiếp tục thiết lập giá trị false cho phương thức setAnimateFirstView để ẩn view đầu tiên trong lần hiển thị đầu tiên.

package hiepsiit.com.viewanimator;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ViewAnimator;

public class MainActivity extends Activity {
	private ViewAnimator simpleViewAnimator;
    Button btnNext;
    // array of images
    int[] images = {R.drawable.lion, R.drawable.cat, R.drawable.dog, R.drawable.bird1, R.drawable.bird2};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// get The references of Button and ViewAnimator
        btnNext = (Button) findViewById(R.id.buttonNext);
        simpleViewAnimator = (ViewAnimator) findViewById(R.id.simpleViewAnimator); // get the reference of ViewAnimator
        for (int i = 0; i < images.length; i++) {
            ImageView imageView = new ImageView(getApplicationContext()); // create a new object  for ImageView
            imageView.setImageResource(images[i]); // set image resource for ImageView
            simpleViewAnimator.addView(imageView); // add child view in ViewAnimator
        }
        // Declare in and out animations and load them using AnimationUtils class
        Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
        Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);

        // set the animation type to ViewAnimator
        simpleViewAnimator.setInAnimation(in);
        simpleViewAnimator.setOutAnimation(out);

        simpleViewAnimator.setAnimateFirstView(false); // set false value for setAnimateFirstView

        // ClickListener for NEXT button
        // When clicked on Button ViewSwitcher will switch between views
        // The current view will go out and next view will come in with specified animation
        btnNext.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                // show the next view of ViewAnimator `     `
                simpleViewAnimator.showNext();
            }
        });
	}
	
}

 


Download ví dụ

Ứng dụng này được phát triển bởi adt bundleandroid 4.2 sử dụng minimum sdk 11  and target sdk 21.


Kết quả khi chạy ứng dụng và kết quả khi click vào "NEXT":