Edittext kotlin get text

Android EditText — Get Text from Edittext and display

In this example tutorial, we’ll look at how to create an EditText and show text in TextView using button click and explore its various properties in Android Studio using the Kotlin language.

What is EditText?
In the app, EditText is used to collect user input. EditText is most commonly used in login and registration form screens.

Implementation:

To begin, Create a new project in android studio with the name EditText Kotlin. Then press the Finish button.
Open the activity main.xml file and add the LinearLayout with orientation (Vertical or horizontal).

xmlns:android=»http://schemas.android.com/apk/res/android»
xmlns:tools=»http://schemas.android.com/tools»
android:orientation=»horizontal»
android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:gravity=»center»
android:background=»#22FFAA00″
tools:context=».MainActivity»>

In activity_main.xml, insert an EditText view inside a LinearLayout.

android:id=»@+id/edittext»
android:layout_width=»300dp»
android:layout_height=»wrap_content»
android:hint=»Enter Username»
android:drawableLeft=»@drawable/user»
android:drawablePadding=»10dp»
android:textColorHint=»@color/white»
android:textColor=»@color/white»
android:drawableTint=»@color/white»
>

Add an drawable to the edittext using the drawableLeft property, hint set using hint attribute.

android:hint=»Enter Username»
android:drawableLeft=»@drawable/user»

EditText has the following attributes:
id, padding, drawablePadding, textColor, textColorHint, background, layout_margin, layout_marginLeft, layout_marginRight, layout_marginEnd, layout margin, paddingLeft etc.

android:layout_marginRight=»20dp»
android:layout_marginLeft=»20dp»
android:padding=»10dp»
android:hint=»Enter Username»
android:drawableLeft=»@drawable/user»
android:drawablePadding=»10dp»
android:textColorHint=»@color/white»
android:textColor=»@color/white»
android:drawableTint=»@color/white»
android:layout_margin=»10dp»

Add Button and TextView below EditText in activity_main.xml file

android:id=»@+id/showBtn»
android:layout_width=»wrap_content»
android:layout_height=»wrap_content»
android:text=»Show»>

android:id=»@+id/textview»
android:layout_width=»wrap_content»
android:layout_height=»wrap_content»
android:layout_marginTop=»30dp»
android:textSize=»29sp»
android:textColor=»@color/white»
android:textStyle=»bold»
>

Now, let’s put our EditText, Button and TextView to use inside Activity. Any view, from layout to activity, can be used by using its unique id: «id» property with findViewById() method.

val edittext = findViewById(R.id.edittext)
val showBtn = findViewById(R.id.showBtn)
val textview = findViewById(R.id.textview)

R.id.edittext is the id of the edittext defined in the activity main.xml file.

Enter some value in the EditText Box and get the text using

val text = edittext.text.toString()

Set the text to TextView with this setText() method

textview.setText(«Text is: » + text)

By implementing onClickListener, we will click on button and set the text on textView.

showBtn.setOnClickListener val text = edittext.text.toString()
textview.setText(«Text is: » + text)
>

Now run the application, you will see the output shown below.

Edittext Example
EditText Example

Complete source code for Android EditText example:

activity_main.xml file

xmlns:android=»http://schemas.android.com/apk/res/android»
xmlns:tools=»http://schemas.android.com/tools»
android:orientation=»vertical»
android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:gravity=»center»
android:background=»#79231D11″
tools:context=».MainActivity»>

android:id=»@+id/edittext»
android:layout_width=»300dp»
android:layout_height=»wrap_content»
android:hint=»Enter Username»
android:drawableLeft=»@drawable/user»
android:drawablePadding=»10dp»
android:textColorHint=»@color/white»
android:textColor=»@color/white»
android:drawableTint=»@color/white»
>

android:id=»@+id/showBtn»
android:layout_width=»wrap_content»
android:layout_height=»wrap_content»
android:text=»Show»>

android:id=»@+id/textview»
android:layout_width=»wrap_content»
android:layout_height=»wrap_content»
android:layout_marginTop=»30dp»
android:textSize=»29sp»
android:textColor=»@color/white»
android:textStyle=»bold»
>

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.*

class MainActivity : AppCompatActivity() override fun onCreate(savedInstanceState: Bundle?) super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val edittext = findViewById(R.id.edittext)
val showBtn = findViewById(R.id.showBtn)
val textview = findViewById(R.id.textview)

showBtn.setOnClickListener val text = edittext.text.toString()
textview.setText(«Text is: » + text)
>
>
>

Conclusion: We have covered the topic how to add EditText to Android and set the text on Textview using Button click event using Kotlin.

Источник

How to get Value of a Edit Text field in Android using Kotlin?

This example demonstrates how to get Value of a Edit Text field in Android using Kotlin?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.kt

import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() < lateinit var button: Button lateinit var editText: EditText lateinit var string: String lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" button = findViewById(R.id.button) editText = findViewById(R.id.editText) textView = findViewById(R.id.textView) button.setOnClickListener < string = editText.text.toString() textView.text = string >> >

Step 4 − Add the following code to androidManifest.xml

Example

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

Источник

Android EditText Tutorial With Example in Kotlin

Android EditText is in an android app basically use for taking input from users. It’s a very useful component(widget or controller) in app development. EditText is a subclass of TextView with text editing operations. The most common example of EditText is in the Login and signup process in the application.

Android EditText Tutorial With Example in Kotlin

In this tutorial, you will learn the following:

  1. An overview and basic of Android EditText
  2. Set EditText and get text example and many basic codes

An attribute android:inputType=»text» is must specify, like for plain text input set inputType to «text» . Why it’s a must? let’s see if your app has to accept a secret number, like a unique pin (password), you can set inputType to “numericPassword”. An inputType of “numericPassword” results in an edit text that accepts numbers only, shows a numeric keyboard.

EditText Syntax:

This is inside a layout resource file XML, you can also define it by pragmatically (java or kotlin)

Retrieving the Value From EditText:

Here is code in kotlin to retrieving the value from EditText in kotlin.

Set Hint in EditText

Setting a Hint in EditText is important, it gives an idea (information) about what to write on.

Set textColor in EditText

It depends on the user to set Text color in Theme or separate in each EditText widget. Always recommend defining value as color and string define in XML file value folders.

Let’s Build a Simple Example of Android EditText

Step 1. Create new project “ Build Your First Android App in Kotlin “
Step 2. Add EditText in resources layout “activity_main.xml

You can add by drag and drop or write direct code in the XML file.

Android EditText add in xml

add fowling code in “activity_main.xml“, we are using Button to show perform get text form EditText and show in a toast.

Step 3. Open the “MainActivity.kt” and add the following code
package `in`.eyehunt.androidedittext import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) >// on click button fun showName(view: View) < //getting text from editText var name = editText.text Toast.makeText(this, name, Toast.LENGTH_LONG).show() >>
Step 4. Now Run the application, in an emulator or On your Android device.

Output screenshot Android EditText example :

Android EditText Tutorial With Example in Kotlin output

Download source code Android EditText in kotlin

Note: This example (Project) is developed in Android Studio 3.1.3. Tested on Android 9 ( Android-P), compile SDK version API 27: Android 8.0 (Oreo)

MinSdkVersion=”26″

TargetSdkVersion=”27″

Coding in Kotlin

Источник

Kotlin Android TextView и EditText – отображение текста

Android TextView и EditText — это пользовательские интерфейсы, которые отображают текст для пользователя в Kotlin.

Ниже показан простой XML-код TextView в макете.

Мы можем получить и изменить содержимое текстового представления, определенного в макете XML в файле класса Котлин, как:

val textView = findViewById(R.id.text_view_id) textView.setText("string").toString() val textViewValue = textView.text

EditText — это пользовательский интерфейс, который используется для ввода и изменения текста. При использовании текста редактирования в макете XML мы должны указать его атрибут inputType, который настраивает клавиатуру в соответствии с упоминанием типа ввода.

Простой XML-код EditText в макете показан ниже.

Мы можем получить и изменить содержимое текста редактирования, определенного в макете XML в файле Kotlin, как:

val editText = findViewById(R.id.editText_id) val editTextValue = editText.text

Пример Kotlin Android TextView и ExitText

В этом примере мы вводим текстовое значение в ExitText и отображаем его значение в TextView при нажатии кнопки.

Мы также наблюдаем за изменениями, сделанными над EditText, используя метод addTextChangedListener() и интерфейс TextWatcher.

Activity_main.xml

В файл activity_main.xml добавьте следующий код.

MainActivity.kt

Добавьте следующий код в класс MainActivity.kt. В этом классе мы получаем значение редактируемого текста и отображаем его в текстовом виде, нажав кнопку. При этом мы также наблюдаем за изменениями, сделанными над EditText, с помощью метода addTextChangedListener() и интерфейса TextWatcher. Чтобы узнать больше о TextWatcher, обратитесь к https://www.javatpoint.com/android-edittext-with-textwatcher.

package example.javatpoint.com.kotlintextviewedittext import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.View import android.widget.TextView import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) button.setOnClickListener()< val inputValue: String = editText.text.toString() if(inputValue == null || inputValue.trim()=="")< Toast.makeText(this,"please input data, edit text cannot be blank",Toast.LENGTH_LONG).show() >else < textView4.setText(inputValue).toString() >> textView5.setOnClickListener()< if(textView4.text.toString() == null || textView4.text.toString().trim()=="")< Toast.makeText(this,"clicked on reset textView,\n output textView already reset",Toast.LENGTH_LONG).show() >else < textView4.setText("").toString() >> editText.addTextChangedListener(object: TextWatcher < override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) < // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. Toast.makeText(applicationContext,"executed before making any change over EditText",Toast.LENGTH_SHORT).show() >override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) < // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. Toast.makeText(applicationContext,"executed while making any change over EditText",Toast.LENGTH_SHORT).show() >override fun afterTextChanged(p0: Editable?) < // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. Toast.makeText(applicationContext,"executed after change made over EditText",Toast.LENGTH_SHORT).show() >>) > >

Источник

Читайте также:  Html text color one word
Оцените статью