การใช้งาน ScrollView

บทความนี้เราจะมาทำการรู้จักกับ ScrollView กันนะครับ Scroll View เป็น View ประเภทหนึ่งครับ ที่สามารถเลื่อนขึ้นลง , ซ้ายขวา ได้ ตามแต่ที่ เราทำการ ตั้งค่า เอาไว้

เรามาดูกันดีกว่าว่า จะใช้งานมันได้อย่างไร เริ่มจากการสร้าง ScrollView ให้สามารถเลื่อนขึ้นลงได้ ขึ้นมาก่อนเลยครับ (อย่าลืมสร้าง Window ขึ้่นมาก่อนนะครับ)
var scrollview = Titanium.UI.createScrollView({ width : Ti.Platform.displayCaps.platformWidth, height: Ti.Platform.displayCaps.platformHeight - 20, showVerticalScrollIndicator: true, contentWidth: Ti.Platform.displayCaps.platformWidth, scrollType :'vertical', // ใช้กับ Android เท่านั้น layout:'horizontal', backgroundColor:'#fff' }); เมื่อได้ ScrollView  แล้วนะครับ เราก็จะมาสร้าง กล่องเล็ก ๆ ที่อยู่ด้านในกัน ในบทความนี้ผมจะสร้างทั้งหมด 30 กล่องนะครับ โดยจะให้แสดงแถวละ 3 กล่อง  แล้วก็ทำการ Add ลงไปให้กับ View
for (var i = 0; i < 30 ; i ++) { var view = Ti.UI.createView({ width: Ti.Platform.displayCaps.platformWidth / 3, height:Ti.Platform.displayCaps.platformWidth / 3, backgroundColor:'#aaa', borderColor:'#000', borderWidth:1, top:0, left:0 }); contentHeight += view.height / 3; scrollview.add(view); } scrollview.contentHeight = contentHeight; // การ Set Content height เนื่องจาก Scroll View บน Android หาก Set content height เป็น  'auto'   จะไม่สามารถเลื่อนขึ้นลงได้ยังไม่ทราบสาเหตุแต่อย่างใด
แล้วก็ทำการนำเอา Scrollview ไปใส่ใน window แล้วก็สั่งให้ window เปิดครับ เมื่อทดลองรันดูก็จะได้ หน้าจอ โปรแกรมแบบนี้ ครับ  ลองทำการ Scroll ดูก็​จะสามารถเลื่อนขึ้นและเลื่อนลงได้



ในกรณีที่ต้องให้ ScrollView นั้น มีการ มีการเลื่อนไปซ้ายขวา ก็​ เปลี่ยน  Code ให้เป็นแบบนี้ครับ
var scrollview = Titanium.UI.createScrollView({ width : Ti.Platform.displayCaps.platformWidth, height: Ti.Platform.displayCaps.platformHeight - 20, showHorizontalScrollIndicator: true, // จากเดิม showVerticalScrollIndicator: true, contentWidth: 'auto', scrollType :'horizontal',  // จากเดิม scrollType :'vertical' layout:'horizontal', backgroundColor:'#fff' }); for (var i = 0; i < 30 ; i ++) { var view = Ti.UI.createView({ width: Ti.Platform.displayCaps.platformWidth / 3, height:Ti.Platform.displayCaps.platformWidth / 3, backgroundColor:'#aaa', borderColor:'#000', borderWidth:1, top:0, left:0 }); scrollview.add(view); }
เมื่อทดลองรันดูก็จะได้ ตามภาพครับ

เป็นอย่างไรกันบ้างครับ กับ ScrollView ที่สามารถเลื่อนได้ทั้ง บน-ล่าง ,​ซ้าย-ขวา  ในบทความหน้าผมจะกล่าวถึง Scrollableview ครับ ส่วนจะเหมือนหรือแตกต่างกับ Scrollview อย่างไรบ้าง ติดตามกันต่อนะครับ

0 ความคิดเห็น:

แสดงความคิดเห็น