2021-07-21

这篇博客介绍了如何在Android应用中,使用Kotlin为EditText添加点击事件,显示一个列表弹窗供用户选择。通过创建ListPopupWindow,动态填充数据并设置点击监听,实现了用户从列表中选取内容后自动填充到EditText的功能。
摘要由CSDN通过智能技术生成

Android Kotlin EditText框点击 获取列表数据

  1. 布局在这里插入代码片
  2. <?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:app=“http://schemas.android.com/apk/res-auto”
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=".MainActivity">

<EditText
    android:id="@+id/ed_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:drawableRight="@mipmap/up"
    android:layout_margin="20dp"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
在这里插入图片描述

3.kotlin 代码 没有data bing 有具体业务需求自己改一下


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val edText = findViewById<EditText>(R.id.ed_tv)
        edText.setOnClickListener(View.OnClickListener {

            showListPopulWindow()

        })
    }


    private lateinit var listPopupWindow: ListPopupWindow //懒加载

    private fun showListPopulWindow() {
        val edText = findViewById<EditText>(R.id.ed_tv)
        val list = arrayOf("item1", "item2", "item3", "item4") //List方法可以自己抽出来动态添加数据
        if (::listPopupWindow.isInitialized.not()) {// 判断 如果有就添加数据,没有创建就new 一个
            listPopupWindow = ListPopupWindow(this)
            listPopupWindow.setAdapter(
                ArrayAdapter(
                    this,
                    android.R.layout.simple_list_item_1,
                    list
                )
            ) //用android内置布局,或设计自己的样式
            listPopupWindow.anchorView = edText //以哪个控件为基准,在该处以logId为基准
            listPopupWindow.isModal = true
            listPopupWindow.setOnItemClickListener { adapterView, view, i, l ->

                //设置项点击监听
                edText.setText(list[i]) //把选择的选项内容展示在EditText上
                listPopupWindow.dismiss() //如果已经选择了,隐藏起来
            }
        }
        listPopupWindow.show() //把ListPopWindow展示出来
    }

```java
在这里插入代码片

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值