最近开发车主相关的App功能, 做一个出行功能大致和高德路线规划功能相当。 对高德的路线规划交做了细致的调研。
功能拆分开来,路线规划逻辑主要涉及:POI搜索和 路线规划; UI部分主要任务在搜索输入框开发, 列表开发, 路线图层开发。 路线的搜索和路线规划及其规划线路绘制方面高德开放平台均有文档详细介绍,就不再细谈了;此篇主要介绍仿高德的路线搜索交互界面的开发,本文简称为路线搜索框开发。
此路线搜索框有两种状态,编辑途径点态和无途径点态;
此外 编辑途径点态还包含拖动地址改变顺序功能。
考虑拖动的交互,Android里常选的方案是RecyclerView实现;但是今天我们采用Tween动画实现拖动的交互效果。 Tween Animation 和属性动画不一样,不改变View的真实属性数据(也就不改变子View真实位置),仅动画效果的显示,可利用此特性来展示拖动时的切换效果,和拖动结束时回到真实状态的一个切换。 利用数据交换来刷新 拖动后台的UI。
UI整体布局采用XML硬编码的形式引入,使用include的方式复用每条位置POI搜索框。
<LinearLayout
android:id="@+id/ll_more_edit_line"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/ll_edit_action"
android:orientation="vertical">
<include
android:id="@+id/ll_start_location"
layout="@layout/edit_search_key" />
<include
android:id="@+id/ll_end_location"
layout="@layout/edit_search_key" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:id="@+id/ll_edit_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_edt"
android:layout_width="@dimen/dp_32"
android:layout_height="@dimen/dp_32"
android:scaleType="centerInside"
android:src="@drawable/start_location_point" />
<EditText
android:id="@+id/edt_input_key"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/iv_edt"
android:background="@color/transparent"
android:hint=""
android:minHeight="@dimen/dp_32"
android:paddingVertical="@dimen/dp_6"
android:singleLine="true"
android:text="@string/confirm"
android:textColor="@color/text_content_first"
android:textColorHint="@color/text_content_five"
android:textSize="@dimen/dp_14" />
<ImageView
android:id="@+id/iv_edit_move_tag"
android:layout_width="@dimen/fit_dp_20"
android:layout_height="@dimen/fit_dp_20"
android:layout_alignRight="@+id/edt_input_key"
android:layout_centerVertical="true"
android:layout_marginRight="@dimen/fit_dp_8"
android:src="@drawable/icon_edit_move"
android:visibility="gone" />
</RelativeLayout>
<ImageView
android:id="@+id/iv_del_edit"
android:layout_width="@dimen/dp_20"
android:layout_height="@dimen/dp_20"
android:layout_gravity="center_vertical"
android:layout_marginLeft="@dimen/dp_8"
android:scaleType="centerInside"
android:src="@drawable/ic_close"
android:visibility="gone" />
</LinearLayout>
新增途径点:
/**
* @param middleIndex 从0开始,排除起点和终点之外的列表
*/
private fun addMiddleLocation(middleIndex: Int = 0): EditText {
val params = LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
val top: Int = resources.getDimensionPixelSize(R.dimen.dp_6)
val bottom = 0
params.topMargin = top
params.bottomMargin = bottom
val middleViewBinding = createMiddleLocationEditView();
var middlePos: Int = middleIndex
if (getMiddleCount() > middleIndex) {
binding.llMoreEditLine.addView(middleViewBinding.root, middleIndex + 1, params)
} else {
val index = binding.llMoreEditLine.childCount - 1;
binding.llMoreEditLine.addView(middleViewBinding.root, index, params)
middlePos = getMiddleCount() - 1;
}
val middleData = EditLocation.createMiddleLocation()
middleViewBinding.root.setTag(R.id.cb_item_tag, middleData)
middleViewBinding.edtInputKey.setTag(R.id.cb_item_tag, middleData)
locationList.add(middlePos + 1, middleData)
updateAddMoreUIState()
post {
middleViewBinding.edtInputKey.requestFocus()
}
return middleViewBinding.edtInputKey
}
删除途径点
/**
* @param middleIndex 从0开始,排除起点和终点之外的列表
*/
private fun removeMiddleLocation(middleIndex: Int) {
getMiddleItemViewAt(middleIndex)?.let { child ->
binding.llMoreEditLine.removeView(child)
(child.getTag(R.id.cb_item_tag) as? EditLocation).let { data ->
locationList.remove(data)
}
}
val count = getMiddleCount()
switchUIState(true, count)
updateAddMoreUIState()
}
长按事件的触发直接在事件分发的顶层拦截触摸事件判断是否长按:
val mainHandler = object : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
when (msg.what) {
MSG_LONG_CLICK -> {
val obj = msg.obj as Point
val windowX = obj.x;
val windowY = obj.y
findLongTouchValidView(windowX, windowY)?.let { findDragView ->
onDragStart(findDragView, msg.arg1, msg.arg2)
}
}
}
}
}
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
var dy = 0f
val tempDragView = dragSelectedView;
when (ev?.action) {
MotionEvent.ACTION_DOWN -> {
yPos = ev.y
mainHandler.removeMessages(MSG_LONG_CLICK)
val msg = mainHandler.obtainMessage(MSG_LONG_CLICK)
msg.arg1 = ev.x.toInt()
msg.arg2 = ev.y.toInt()
msg.obj = Point(ev.rawX.toInt(), ev.rawY.toInt())
mainHandler.sendMessageDelayed(msg, LONG_TIME)
}
MotionEvent.ACTION_MOVE -> {
dy = ev.y - yPos;
yPos = ev.y
if (tempDragView != null && dy != 0f) {
mainHandler.removeMessages(MSG_LONG_CLICK)
onDragMove(tempDragView!!, ev.x.toInt(), ev.y.toInt(), dy)
}
}
MotionEvent.ACTION_CANCEL -> {
mainHandler.removeMessages(MSG_LONG_CLICK)
if (tempDragView != null) {
onDragEnd()
}
}
MotionEvent.ACTION_UP -> {
mainHandler.removeMessages(MSG_LONG_CLICK)
if (tempDragView != null) {
onDragEnd()
}
}
}
if (tempDragView != null) {
return true
}
return super.dispatchTouchEvent(ev);
}
拖动的View是一个可以悬浮在容器之上的空间中, 需要定义一个View来显示拖拽的目标View,这里采用的是ImageView; 把即将拖拽的View生成对应Bitmap来显示到悬浮的ImageView中,并把悬浮的位置设定在拖拽View的位置,实现拖拽重合移动效果。 代码片段如下:
/**
* 开始拖拽,在长按事件触发之后
*/
private fun onDragStart(dragItemVIew: View, touchX: Int, touchY: Int) {
try {
if (itemEditHeight != 0 && isDragEnable()) {
val itemView = dragItemVIew
val vImage = vToBitmap(itemView)
floatView.setImageBitmap(vImage)
val top = itemView.top + ((itemView.parent as? View)?.top ?: 0)
Log.w(TAG, "top === $top");
floatView.tag = top;
setViewTopMargin(floatView, top)
floatView.visibility = View.VISIBLE
itemView.visibility = INVISIBLE
dragSelectedView = itemView;
dragInsertViewStack.clear();
resetItemViewRectInfo()
ClickVibrator.clickSingle(context, 100L)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* 拖拽移动
*/
private fun onDragMove(dragItemVIew: View, touchX: Int, touchY: Int, dy: Float) {
val newTop: Int = floatView.tag as Int + dy.toInt()
val newBottom: Int = newTop + itemEditHeight;
if (newTop in minDragTop..maxDragTop) {
floatView.tag = newTop
setViewTopMargin(floatView, newTop)
//碰撞检测
for (rect in itemRectHashMap.keys) {
val line = rect.top + rect.height() / 2
val itemView = itemRectHashMap.get(rect)
if (itemView == dragSelectedView) {
continue
}
if (line in newTop..newBottom) {
//发生碰撞
val dTop = line - newTop;
val dBottom = newBottom - line;
Log.w(TAG, "move === $dTop -- $dBottom")
val fromTop = rect.top;
val animDistance = rect.height() + resources.getDimensionPixelSize(R.dimen.dp_6)
if (dTop < dBottom) {
//item down
post {
val destTop = fromTop + animDistance
itemView?.let {
itemRectHashMap.remove(rect)
val newRect =
Rect(rect.left, destTop, rect.right, destTop + itemEditHeight)
itemRectHashMap.put(newRect, itemView)
trans(itemView, rect, newRect)
}
}
} else {
//item up
post {
val destTop = fromTop - animDistance
itemView?.let {
itemRectHashMap.remove(rect)
val newRect =
Rect(rect.left, destTop, rect.right, destTop + itemEditHeight)
itemRectHashMap.put(newRect, itemView)
trans(itemView, rect, newRect)
}
}
}
break;
}
}
}
}
/**
* 拖拽结束
*/
private fun onDragEnd() {
val replaceView = if (dragInsertViewStack.isEmpty()) null else dragInsertViewStack.pop()
if (dragSelectedView != null && replaceView != null) {
val dragData = dragSelectedView?.getTag(R.id.cb_item_tag) as? EditLocation
val replaceData = replaceView.getTag(R.id.cb_item_tag) as? EditLocation
callEditLocationDataChange(dragData, replaceData)
}
clearDragUIState()
}
平移动画实现,需要注意的是:平移的参数主要是相对View的原始位置 计算上下移动的位置。 所以需要改根据位置计算坐标变换。
private fun trans(item: View?, fromRect: Rect, toRect: Rect) {
val divideTop = binding.rlEditLocationContainer.top
val fromTop = fromRect.top - divideTop
val destTop = toRect.top - divideTop
val originTop = (item?.top ?: 0) + ((item?.parent as? View)?.top ?: 0)
val animationDis = destTop - fromTop
val moveOut = originTop == fromTop
if (moveOut) {
dragInsertViewStack.push(item)
} else if (!dragInsertViewStack.isEmpty()) {
dragInsertViewStack.pop();
}
val fromY = if (moveOut) 0 else -1 * animationDis
val toY = if (moveOut) animationDis else 0;
Log.w(TAG, "trans start == $originTop --- $fromY,$toY")
val tran = TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
Animation.ABSOLUTE, fromY.toFloat(), Animation.ABSOLUTE, toY.toFloat()
)
tran.duration = (300L)
tran.fillAfter = true;
item?.startAnimation(tran)
}
在拖动结束时清空所用动画和 计算交换后的数据,重新更新对应位置的显示数据。
private fun callEditLocationDataChange(dragData: EditLocation?, replaceData: EditLocation?) {
if (dragData == null || replaceData == null) {
return;
}
val tempList = ArrayList<EditLocation>();
val tempPoiList = ArrayList<EditLocation>();
tempList.addAll(locationList)
val dragIndex = tempList.indexOf(dragData)
val replaceIndex = tempList.indexOf(replaceData);
if (dragIndex != -1 && replaceIndex != -1 && dragIndex != replaceIndex) {
tempList.removeAt(dragIndex);
val insertIndex = tempList.indexOf(replaceData);
if (insertIndex != -1) {
val addIndex = if (dragIndex > replaceIndex) insertIndex else insertIndex + 1
tempList.add(addIndex, dragData)
}
if (tempList.size == locationList.size) {
for (item in tempList) {
val temp = EditLocation()
temp.poi = item.poi;
temp.editContent = item.editContent
tempPoiList.add(temp)
}
for (i in 0 until locationList.size) {
val item = locationList[i]
val tempData = tempPoiList[i]
item.poi = tempData.poi;
item.editContent = tempData.editContent
val tv = findLocationTextView(i)
updateLocationUI(item, tv)
}
}
}
tempList.clear()
tempPoiList.clear()
}
private fun clearDragUIState() {
dragSelectedView?.visibility = View.VISIBLE
floatView.visibility = View.GONE
dragSelectedView = null
for (i in 0 until binding.llMoreEditLine.childCount) {
binding.llMoreEditLine.getChildAt(i)?.clearAnimation()
}
dragInsertViewStack.clear()
}
最终的效果: