

init {
linear = LinearLayout(context)
linear.orientation = LinearLayout.HORIZONTAL
val params = LinearLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT)
params.leftMargin = CommonUtil.dp2px(context, 15f)
linear.gravity = Gravity.CENTER_VERTICAL
this.addView(linear, params)
}
fun onClicked(index: Int) {
if (index == -1) {
return
}
this.post({
val position = index
val itemView = linear.getChildAt(position)
val itemWidth = itemView.width
val screenWidth = CommonUtil.getScreenWidth(context)
val newPosition = itemView.left - (screenWidth / 2 - itemWidth / 2)
val scrollBy = newPosition - lastPosition
lastPosition = newPosition
smoothScrollBy(scrollBy, 0)
})
}
fun removeAllItemViews() {
linear.removeAllViews()
}
fun addItemView(itemView: View, params: LinearLayout.LayoutParams) {
linear.addView(itemView, params)
}
}
在xml中这样引用:
<ctrip.android.tour.priceCalendar.component.CenterShowHorizontalScrollView
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:id="@+id/multiline_layout"
android:background="#ffffff"
android:scrollbars=“none”>
</ctrip.android.tour.priceCalendar.component.CenterShowHorizontalScrollView>
在java文件中注意在addView到这个自定义的HorizontalScrollView中时,要调用addItemView方法。然后在选中item时,调用onClicked方法。