首页 > 解决方案 > 没有得到编辑文本数据

问题描述

我是安卓新手。我不知道如何在 Android 中获取 EditText 的数据。

这是我的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
   android:orientation="vertical"
   tools:context=".MainActivity2">
   <EditText
     android:id="@+id/edOne"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"/>
   <EditText
     android:id="@+id/edSecond"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"/>
   <Button
    android:id="@+id/btnAdd"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</LinearLayout>

这是我的代码:

    val one=edOne.text.toString()
    btnAdd.setOnClickListener{
        val two=edOne.text.toString()
       Log.e("Tag",one +" "+two)
    }

标签: android

解决方案


一种是从 onCreate() 方法调用。并且在您创建 onCreate() 时,您在 editText one 中没有任何数据。因此,如果您没有从 xml 添加,则无法从其中获取任何数据。

因此,只需将您的一个代码移动到点击侦听器中。

val one=edOne.text.toString()
btnAdd.setOnClickListener{
    val two=edOne.text.toString()
   Log.e("Tag",one +" "+two)
}

推荐阅读