Lập trình Android - HorizontalScrollView

HorizontalScrollView trong Android

Trong Android chúng ta có thể cuộn các view  theo chiều ngang hoặc chiều thẳng đứng. Nếu cuộn theo chiều thẳng đứng chúng ta dùng ScrollView, còn cuộn theo chiều ngang chúng ta dùng HorizontalScrollView.


Cú pháp tạo HorizontalScrollView trong XML:

<HorizontalScrollView
android:id="@+id/horizontalscrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<-- add child view’s here -->

</HorizontalScrollView >

Thuộc tính thường dùng của HorizontalScrollView

Các thuộc tính của HorizontalScrollView  giống ScrollView
1. android:id: 
Là thuộc tính duy nhất của HorizontalScrollView .

<HorizontalScrollView
android:id="@+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>

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:

HorizontalScrollView simpleHorizontalScrollView = (ScrollView ) findViewById(R.id.simpleHorizontalScrollView );

2. android:scrollbars: Thuộc tính này được sử dụng hiển thị thanh cuộn trong ScrollView, giá trị có thể là "vertical, horizontal" Mặc định cuộn theo thẳng đứng. 

< HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"/><!--scrollbars in vertical direction-->

Ví dụ: Trong ví dụ này chúng ta sẽ làm ứng dụng gồm có một HorizontalScrollView. Trong HorizontalScrollView có 10 button và cuộn theo chiều ngang.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à HorizontalScrollViewFile->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  Relative Layout.
Chú ý: ScrollView chỉ điều khiển trực tiếp một con, nên để cuộn 10 button chúng ta phải đặt chúng trong Layout

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

package hiepsiit.com.scrollview;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

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

}

 


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