UI 仿高德路線規(guī)劃搜索交互

最近開發(fā)車主相關(guān)的App功能, 做一個出行功能大致和高德路線規(guī)劃功能相當(dāng)。 對高德的路線規(guī)劃交做了細(xì)致的調(diào)研。
功能拆分開來,路線規(guī)劃邏輯主要涉及:POI搜索和 路線規(guī)劃; UI部分主要任務(wù)在搜索輸入框開發(fā), 列表開發(fā), 路線圖層開發(fā)。 路線的搜索和路線規(guī)劃及其規(guī)劃線路繪制方面高德開放平臺均有文檔詳細(xì)介紹,就不再細(xì)談了;此篇主要介紹仿高德的路線搜索交互界面的開發(fā),本文簡稱為路線搜索框開發(fā)。

此路線搜索框有兩種狀態(tài),編輯途徑點(diǎn)態(tài)和無途徑點(diǎn)態(tài);


image.png

image.png

此外 編輯途徑點(diǎn)態(tài)還包含拖動地址改變順序功能。
考慮拖動的交互,Android里常選的方案是RecyclerView實現(xiàn);但是今天我們采用Tween動畫實現(xiàn)拖動的交互效果。 Tween Animation 和屬性動畫不一樣,不改變View的真實屬性數(shù)據(jù)(也就不改變子View真實位置),僅動畫效果的顯示,可利用此特性來展示拖動時的切換效果,和拖動結(jié)束時回到真實狀態(tài)的一個切換。 利用數(shù)據(jù)交換來刷新 拖動后臺的UI。

UI整體布局采用XML硬編碼的形式引入,使用include的方式復(fù)用每條位置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>

新增途徑點(diǎn):

    /**
     * @param middleIndex 從0開始,排除起點(diǎn)和終點(diǎn)之外的列表
     */
    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
    }

刪除途徑點(diǎn)

    /**
     * @param middleIndex 從0開始,排除起點(diǎn)和終點(diǎn)之外的列表
     */
    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()
    }

長按事件的觸發(fā)直接在事件分發(fā)的頂層攔截觸摸事件判斷是否長按:

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來顯示拖拽的目標(biāo)View,這里采用的是ImageView; 把即將拖拽的View生成對應(yīng)Bitmap來顯示到懸浮的ImageView中,并把懸浮的位置設(shè)定在拖拽View的位置,實現(xiàn)拖拽重合移動效果。 代碼片段如下:

/**
     * 開始拖拽,在長按事件觸發(fā)之后
     */
    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) {
                    //發(fā)生碰撞
                    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;
                }
            }
        }
    }
/**
     * 拖拽結(jié)束
     */
    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()
    }

平移動畫實現(xiàn),需要注意的是:平移的參數(shù)主要是相對View的原始位置 計算上下移動的位置。 所以需要改根據(jù)位置計算坐標(biāo)變換。

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)
    }

在拖動結(jié)束時清空所用動畫和 計算交換后的數(shù)據(jù),重新更新對應(yīng)位置的顯示數(shù)據(jù)。

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容