EditText.kt 2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
 * Copyright 2019 New Vector Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
package im.vector.app.core.extensions
18
19
20
21
22
23
24

import android.text.Editable
import android.text.InputType
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
ganfra's avatar
ganfra committed
25
import androidx.annotation.DrawableRes
26
27
import im.vector.app.R
import im.vector.app.core.platform.SimpleTextWatcher
28

29
fun EditText.setupAsSearch(@DrawableRes searchIconRes: Int = R.drawable.ic_search,
Onuray Sahin's avatar
Onuray Sahin committed
30
                           @DrawableRes clearIconRes: Int = R.drawable.ic_x_gray) {
Benoit Marty's avatar
Benoit Marty committed
31
32
33
    addTextChangedListener(object : SimpleTextWatcher() {
        override fun afterTextChanged(s: Editable) {
            val clearIcon = if (s.isNotEmpty()) clearIconRes else 0
ganfra's avatar
ganfra committed
34
            setCompoundDrawablesWithIntrinsicBounds(searchIconRes, 0, clearIcon, 0)
35
36
37
38
39
40
        }
    })

    maxLines = 1
    inputType = InputType.TYPE_CLASS_TEXT
    imeOptions = EditorInfo.IME_ACTION_SEARCH
Benoît Marty's avatar
Benoît Marty committed
41
    setOnEditorActionListener { _, actionId, _ ->
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
        var consumed = false
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            hideKeyboard()
            consumed = true
        }
        consumed
    }

    setOnTouchListener(View.OnTouchListener { _, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            if (event.rawX >= (this.right - this.compoundPaddingRight)) {
                text = null
                return@OnTouchListener true
            }
        }
        return@OnTouchListener false
    })
}