UI 仿高德路线规划搜索交互

最近开发车主相关的App功能, 做一个出行功能大致和高德路线规划功能相当。 对高德的路线规划交做了细致的调研。
功能拆分开来,路线规划逻辑主要涉及:POI搜索和 路线规划; UI部分主要任务在搜索输入框开发, 列表开发, 路线图层开发。 路线的搜索和路线规划及其规划线路绘制方面高德开放平台均有文档详细介绍,就不再细谈了;此篇主要介绍仿高德的路线搜索交互界面的开发,本文简称为路线搜索框开发。

此路线搜索框有两种状态,编辑途径点态和无途径点态;


image.png

image.png

此外 编辑途径点态还包含拖动地址改变顺序功能。
考虑拖动的交互,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()
    }

最终的效果:


ezgif-2-6c18732c34.gif
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,264评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,549评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,389评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,616评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,461评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,351评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,776评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,414评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,722评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,760评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,537评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,381评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,787评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,030评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,304评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,734评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,943评论 2 336

推荐阅读更多精彩内容