11package com.tool.tree
22
3+ import android.annotation.SuppressLint
34import android.content.Context
45import android.content.Intent
56import android.graphics.Typeface
@@ -12,6 +13,7 @@ import android.util.TypedValue
1213import android.view.Gravity
1314import android.view.Menu
1415import android.view.MenuItem
16+ import android.view.MotionEvent
1517import android.view.View
1618import android.view.ViewGroup
1719import android.view.inputmethod.InputMethodManager
@@ -313,19 +315,59 @@ class TextEditorActivity : AppCompatActivity() {
313315 }
314316 }
315317
318+ @SuppressLint(" ClickableViewAccessibility" )
316319 private fun setupEditorTouchAndFocus () {
317320 val focusAndShowKeyboard = {
318321 binding.editorContent.requestFocus()
319322 val imm = getSystemService(Context .INPUT_METHOD_SERVICE ) as ? InputMethodManager
320323 imm?.showSoftInput(binding.editorContent, InputMethodManager .SHOW_IMPLICIT )
324+ }
325+
326+ binding.mainListText.setOnClickListener {
327+ focusAndShowKeyboard()
328+ if (binding.editorContent.selectionStart < 0 ) {
329+ binding.editorContent.setSelection(binding.editorContent.text?.length ? : 0 )
330+ }
331+ }
332+
333+ binding.editorContentContainer.setOnClickListener {
334+ focusAndShowKeyboard()
321335 if (binding.editorContent.selectionStart < 0 ) {
322336 binding.editorContent.setSelection(binding.editorContent.text?.length ? : 0 )
323337 }
324338 }
325339
326- binding.mainListText.setOnClickListener { focusAndShowKeyboard() }
327- binding.editorLineNumbers.setOnClickListener { focusAndShowKeyboard() }
328- binding.editorContentContainer.setOnClickListener { focusAndShowKeyboard() }
340+ // Xử lý khi nhấn vào khu vực số dòng -> đặt con trỏ về đầu dòng tương ứng
341+ binding.editorLineNumbers.setOnTouchListener { v, event ->
342+ if (event.action == MotionEvent .ACTION_UP ) {
343+ v.performClick()
344+ focusAndShowKeyboard()
345+
346+ val editText = binding.editorContent
347+ val layout = editText.layout
348+ val text = editText.text
349+
350+ if (layout != null && ! text.isNullOrEmpty()) {
351+ // Quy đổi tọa độ Y tương ứng với EditText
352+ val yInEditText = event.y + binding.editorLineNumbers.top - editText.top
353+ val yInLayout = yInEditText - editText.paddingTop
354+ val clampedY = yInLayout.coerceIn(0f , (layout.height - 1 ).toFloat())
355+
356+ // Xác định dòng được nhấn
357+ val line = layout.getLineForVertical(clampedY.toInt())
358+
359+ // Tìm vị trí ký tự đầu dòng logic (hoạt động tốt cả khi bật Word Wrap)
360+ var lineStart = layout.getLineStart(line)
361+ while (lineStart > 0 && text[lineStart - 1 ] != ' \n ' ) {
362+ lineStart--
363+ }
364+
365+ // Đặt con trỏ về đầu dòng
366+ editText.setSelection(lineStart.coerceIn(0 , text.length))
367+ }
368+ }
369+ true
370+ }
329371 }
330372
331373 private fun setupUnifiedTextWatcher () {
0 commit comments