Lập trình Android - ViewSwitcher

ViewSwitcher trong Android

trong Android, ViewSwitcher là một lớp con của lớp ViewAnimator được sử dụng để chuyển đổi giữa các view. Đây là một phần của tiện ích chuyển tiếp giữa các view có các widget. Nó chủ yếu để hiệu ứng một view trên màn hình. ViewSwitcher chuyển một cách mượt mà giữa hai view (tức là TextView, ImageView hoặc bất kỳ Layout nào) và do đó cung cấp cách chuyển từ chế độ view này sang chế độ view khác thông qua các hoạt ảnh thích hợp. 

ViewSwitcher chỉ có thể có hai view con và chỉ có thể hiển thị một lần trong một thời điểm. Nếu bạn có nhiều hơn hai view con trong ViewSwitcher sẽ xảy ra lỗi: “Can’t add more than 2 views to a ViewSwitcher” .


TextSwitcher code trong XML:

<ViewSwitcher

android:id="@+id/viewswitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<!--   Thêm 2 Views -- >

</ViewSwitcher>

Các bước tạo ViewSwitcher

Bước 1: Khởi tạo ImageSwitcher 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 ViewSwitcher

Sau đây là các phương thức quan trọng thường được sử dụng để quản lý ViewSwitcher

1. getNextView(): Phương thức này trả về view kế tiếp để thị trong ViewSwitcher. Giá trị trả về là id của view kế tiếp.

Ví dụ sau lấy id của view tiếp theo để hiển thị trong ViewSwitcher.

ViewSwitcher simpleViewSwitcher = (ViewSwitcher) findViewById(R.id.simpleViewSwitcher); // get the reference of ViewSwitcher
View nextView=simpleViewSwitcher.getNextView(); // get next view to be displayed

2. reset(): Phương thức này thường sử dụng để thiết lập trạng thái ban đầu của ViewSwitcher.

Ví dụ sau thiết lập lại trạng thái ban đầu cho ViewSwitcher, dấu tất cả các view đang tồn tại

ViewSwitcher simpleViewSwitcher = (ViewSwitcher) findViewById(R.id.simpleViewSwitcher); // get the reference of ViewSwitcher

simpleViewSwitcher.reset(); // reset the ViewSwitcher to hide all of the existing views

3. showNext(): Phương thức này thường sử dụng hiển thị view kế tiếp của ViewSwitcher. Như chúng ta đã biết thì ViewSwitcher chỉ có 2 view con và tại một thời điểm chỉ hiển thị một view.

Ví dụ sau khi click vào button sẽ gọi phương thức showNext() để hiển thị view tiếp theo lên ViewSwitcher

ViewSwitcher simpleViewSwitcher = (ViewSwitcher) findViewById(R.id.simpleViewSwitcher); // get the reference of ViewSwitcher

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 ViewSwitcher
simpleViewSwitcher.showNext();
}
});

4. showPrevious(): Phương thức này thường sử dụng hiển thị view trước của ViewSwitcher. Như chúng ta đã biết thì ViewSwitcher chỉ có 2 view con và tại một thời điểm chỉ hiển thị một view.

Ví dụ sau khi click vào button gọi phương thức showPrevious() để hiển thị view trước đó lên ViewSwitcher.

ViewSwitcher simpleViewSwitcher = (ViewSwitcher) findViewById(R.id.simpleViewSwitcher); // get the reference of ViewSwitcher

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 previouus view of ViewSwitcher
simpleViewSwitcher.showPrevious();
}
});

5. 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

Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left); // load an animation by using AnimationUtils clas

6. 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 ViewSwitcher

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

7. 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 TextSwitcher.

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

8. setFactory(ViewFactory factory): Phương thức này dùng tạo mới một View cho TextSwitcher. Bằng cách dùng phương thức này chúng ta tạo mới một View mới và thay thế View cũ.

Ví dụ sau sử dụng phương thức setFactory để tạo View mới

ViewSwitcher simpleViewSwitcher=(ViewSwitcher)findViewById(R.id. simpleViewSwitcher); // get reference of ViewSwitcher

// Set the ViewFactory of the ViewSwitcher that will create a new view ( ImageView ) object when asked
simpleViewSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

public View makeView() {
// TODO Auto-generated method stub

// Create a new ImageView and set it's properties
ImageView imageView = new ImageView(getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
return imageView;
}
});

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

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

<ViewSwitcher

android:id="@+id/viewswitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content" > <!--  id of ViewSwitcher that is used to uniquely identify it -->

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

</ViewSwitcher>

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:

ViewSwitcher simpleViewSwitcher=(ViewSwitcher)findViewById(R.id. simpleViewSwitcher); // get reference of ViewSwitcher

2. android:padding: Thuộc tính này xác định khoảng cách từ đường viền của ViewSwitcher 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 ViewSwitcher .

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

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

</ViewSwitcher>

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

Code sau chúng ta thiết lập màu nền, màu xanh cho ViewSwitcher 

<ViewSwitcher
android:id="@+id/simpleViewSwitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#0f0"> <!-- set green color in the background of ViewSwitcher -->

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

</ViewSwitcher>

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

ViewSwitcher simpleViewSwitcher=(ViewSwitcher)findViewById(R.id. simpleViewSwitcher); // get reference of ViewSwitcher
simpleViewSwitcher.setBackgroundColor(Color.GREEN);// set green color in the background of ImageSwitcher.

Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có một ViewSwitcher có 2 View. Một View chứa ImageView và một view chứa Layout gồm có TextView Button, trong ví dụ này cũng có một Button khi người sử dụng click vào Button sẽ chuyển qua view 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à ViewSwitcherFile->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 trong Linear Layout.

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

<!-- ViewSwitcher with two views one is ImageView and other is LinearLayout in which we have a Button and a TextView -->
<ViewSwitcher
android:id="@+id/simpleViewSwitcher"
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:src="@drawable/image" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LinearLayout 2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="- Button 2 -" />


</LinearLayout>
</ViewSwitcher>


<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="150dp"
android:background="#005"
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 ViewSwitcher Button. Trước tiên, chúng ta load và thiết lập các thanh trượt bên trái và bên phải  và cuối cùng thiết lập sự kiện cho Button Khi người sử dụng click vào button "NEXT" chuyển đổi giữa 2 View

package com.example.viewswitcher;

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.ViewSwitcher;

public class MainActivity extends Activity {
	private ViewSwitcher simpleViewSwitcher;
	Button btnNext;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// get The references of Button and ViewSwitcher
		btnNext = (Button) findViewById(R.id.btnNext);
		simpleViewSwitcher = (ViewSwitcher) findViewById(R.id.simpleViewSwitcher); // get the reference of ViewSwitcher
		// 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 ViewSwitcher
		simpleViewSwitcher.setInAnimation(in);
		simpleViewSwitcher.setOutAnimation(out);


		// 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 ViewSwitcher
		simpleViewSwitcher.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: