Android开发教程仿bilibili搜索功能

Android开发教程仿bilibili搜索功能

搜索功能一般都有输入内容后,出现删除图标,点击可以删除内容。软键盘上也出现搜索键

一、思路:

自定义控件PowerfulEditText

二、效果图:

在这里插入图片描述

三、关键代码:
class MainActivity : AppCompatActivity() {

    private lateinit var search_edit:PowerfulEditText
    private lateinit var search_button:TextView
    private lateinit var context: Context

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context= this
        search_edit = findViewById(R.id.search_edit)
        search_button = findViewById(R.id.search_button)

        ShapeUtils.setShapeCorner2Color(search_edit, R.color.c_f2efef, dip2pxBackFloat(this, 18f))
        search_button.setTextColor(resources.getColor(R.color.c_33))
        search_button.setText(R.string.search)

        search_edit.addTextListener(object : PowerfulEditText.TextListener {
            override fun onTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        search_edit.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    startSearch()
                    return true
                }
                return false
            }

        })

        search_button.setOnClickListener {
            startSearch()
        }
    }

    /**
     * @desc : 点击搜索
     * @author : congge on 2019/12/5 14:56
     **/
    private fun startSearch() {
        val keyWord = if (!TextUtils.isEmpty(search_edit.text.toString())){
            search_edit.text.toString()
        } else {
            search_edit.hint.toString()
        }
        //预防输入空格
        if (keyWord.isBlank()){
            Toast.makeText(context,"请输入搜索内容",Toast.LENGTH_SHORT).show()
            return
        }
        Toast.makeText(context,"搜索:${keyWord}",Toast.LENGTH_SHORT).show()

    }

    fun dip2pxBackFloat(context: Context?, dpValue: Float): Float {
        val scale = context?.resources?.displayMetrics?.density
        return (dpValue * scale!! + 0.5f)
    }
}
四、项目demo源码结构图:

在这里插入图片描述有问题或者需要完整源码私信我

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

893151960

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值