Android視頻教程,使用Kotlin的Android TextView –全面教程

 2023-11-19 阅读 27 评论 0

摘要:Kotlin is the official programming language for Android apps development. In this tutorial, we’ll be discussing TextViews in Android applications using Kotlin programming. We’ll create and change TextViews code in Kotlin programming. Kotlin是用于Android

Kotlin is the official programming language for Android apps development. In this tutorial, we’ll be discussing TextViews in Android applications using Kotlin programming. We’ll create and change TextViews code in Kotlin programming.

Kotlin是用于Android應用程序開發的官方編程語言。 在本教程中,我們將討論使用Kotlin編程的Android應用程序中的TextView。 我們將在Kotlin編程中創建和更改TextViews代碼。

Android TextView概述 (Android TextView Overview)

Android TextView is a subclass of the View class. The View class typically occupy our window. TextView is used to display text on the screen. We can do a lot of fancy things using TextView.

Android TextView是View類的子類。 View類通常占據我們的窗口。 TextView用于在屏幕上顯示文本。 我們可以使用TextView做很多花哨的事情。

Android視頻教程,Let’s start with a fresh project in Android Studio.

讓我們從Android Studio中的一個新項目開始。

Create a new project and make sure you’ve enabled Kotlin in the setup wizard.

創建一個新項目,并確保已在設置向導中啟用Kotlin。

在XML布局中創建TextView (Creating TextView in XML Layout)

TextView is created in an xml layout in the following manner.

java調用kotlin, TextView以以下方式在xml布局中創建。

<TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!" />

The four attributes defined above are the core attributes of the TextView widget.

上面定義的四個屬性是TextView小部件的核心屬性。

  1. The id property is used to set a unique identifier. It’s set as @+id/ followed by the name you assign. The same name would be used to retrieve the TextView property in our Kotlin Activity class.

    id屬性用于設置唯一標識符。 設置為@+id/后跟您分配的名稱。 在我們的Kotlin Activity類中,將使用相同的名稱來檢索TextView屬性。
  2. The text property is used to set the string text to be displayed in the TextView.

    text屬性用于設置要在TextView中顯示的字符串文本。
  3. As it is evident from the names itself, layout_width and layout_height are used to set the boundaries of the TextView. The wrap_content means wrapping the width, height to the length of the text. The match_parent means the TextView matches the width/height of the enclosed parent view. We can also set hardcoded values in dp (device independent pixels).

    從名稱本身可以明顯看出,layout_width和layout_height用于設置TextView的邊界。 wrap_content表示將寬度,高度包裝為文本的長度。 match_parent表示TextView與封閉的父視圖的寬度/高度匹配。 我們還可以設置dp(與設備無關的像素)中的硬編碼值。

Clean Code Tips: Instead of hardcoding the string, define it inside the strings.xml and set the text in the layout as follows.

干凈的代碼提示 :不用對字符串進行硬編碼,而是在strings.xml內定義它,并按如下所示在布局中設置文本。

android:text="@string/app_name"

Android10?Let’s apply some attributes over the TextView in XML.

讓我們在XML的TextView上應用一些屬性。

TextView XML屬性 (TextView XML Attributes)

Let’s give you a quick tour of some of the popular attributes of TextView widget.

讓我們快速瀏覽一下TextView小部件的一些流行屬性。

  • android:textSize: sets the size of the TextView. It’s recommended to use sp instead of dp. The sp stands for scale independent pixels and scales the font. Example: 16sp.

    android:textSize :設置TextView的大小。 建議使用sp代替dp。 sp代表與比例無關的像素并縮放字體。 示例:16sp。
  • The android:textColor is used to set a color for the text. Typically it is of the format #rgb, #rrggbb, #aarrggbb.

    android:textColor用于設置文本的顏色。 通常,其格式為#rgb,#rrggbb,#aarrggbb。
  • The android:background attribute is used to set the background color of the TextView.

    android:background屬性用于設置TextView的背景顏色。
  • The android:textStyle is used to set the style among bold, italic, and normal. If you want to set bold and italic, use android:textStyle = “bold|italic”.

    android:textStyle用于在粗體,斜體和普通之間設置樣式。 如果要設置粗體和斜體,請使用android:textStyle =“ bold | italic”。
  • The android:textAppearance attribute is used to set the style on a TextView, which includes its own color, font, and size. We can create custom styles in the styles.xml file.

    android:textAppearance屬性用于在TextView上設置樣式,該樣式包括其自己的顏色,字體和大小。 我們可以在styles.xml文件中創建自定義樣式。
  • android:visibility is used to set the visibililty of the text, possible values are visible, invisible, and gone. The gone makes the textview invisible and removes it from the current position in the layout.

    android:visibility用于設置文本的可見性,可能的值是visibleinvisiblegonegone使textview不可見,并將其從布局中的當前位置刪除。
  • The android:ellipsize is used to handle situations when the length of the text exceeds the limit.

    android:ellipsize用于處理文本長度超過限制的情況。
  • android textview ellipisize.
  • The end adds dots when the text reaches the limit width of the TextView. The start adds the dots at the beginning. The marquee is used to make the text continously slide left and right to show the full text.

    當文本達到TextView的限制寬度時, end添加點。 startstart添加點。 marquee用于使文本連續左右滑動以顯示全文。
  • The android:onClick is the method name in the Kotlin Activity class that’ll be invoked on TextView click. We need to ensure android:clickable is set to true for this attribute.

    android:onClick是Kotlin Activity類中的方法名稱,它將在TextView click上調用。 我們需要確保將此屬性的android:clickable設置為true。
  • android:typeface is used to set the typeface of the text.

    android:typeface用于設置文本的字體。
  • android:drawableLeft is used to set a drawable/mipmap image or vector asset besides the TextView.

    android:drawableLeft用于設置TextView之外的drawable / mipmap圖像或矢量資源。
  • The android:gravity is used to set the position of the text relative to its dimensions.

    android:gravity用于設置文本相對于其尺寸的位置。
  • android:layout_margin is used to set the spacing of the TextView from the other views present in the layout. The layout_marginLeft, layout_marginRight, layout_marginTop, layout_marginBottom are used for setting margins on the individiual sides.

    android:layout_margin用于設置TextView與布局中其他視圖的間距。 layout_marginLeft,layout_marginRight,layout_marginTop,layout_marginBottom用于在各個面上設置邊距。
  • The android:padding is used to add spacing inside the four sides of the TextView. The possible values are paddingLeft, paddingRight, paddingTop, and paddingBottom.

    android:padding用于在TextView的四個側面內添加間距。 可能的值為paddingLeft,paddingRight,paddingTop和paddingBottom。

Android、Let’s use the xml attributes on a TextView in our layout.

讓我們在布局中的TextView上使用xml屬性。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:id="@+id/linearLayout"android:orientation="vertical"tools:context="net.androidly.androidtextviewkotlin.MainActivity"><TextViewandroid:id="@+id/textViewEllipsize"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginBottom="8dp"android:ellipsize="end"android:maxLines="1"android:text="@string/long_string"android:textSize="18sp" /><TextViewandroid:id="@+id/textViewClickMe"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginBottom="8dp"android:background="@color/colorPrimaryDark"android:padding="@android:dimen/app_icon_size"android:shadowColor="@android:color/black"android:text="TextView Click Me" /><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Android TextView Color"android:textAllCaps="true"android:textAppearance="?android:attr/textAppearanceLarge"android:textColor="#234568"android:textStyle="bold|italic" /><TextViewandroid:id="@+id/textViewOpacity"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="16dp"android:drawableLeft="@mipmap/ic_launcher"android:drawablePadding="16dp"android:gravity="center"android:text="Android TextView Opacity is 50 percent"android:textColor="#50234568"android:textSize="14sp"android:typeface="serif" /></LinearLayout>

Note: We’ve replaced the ConstraintLayout with a LinearLayout to make things easier.

注意:我們已經使用LinearLayout替換了ConstraintLayout,使事情變得更容易。

android textview XML output

Notice the opacity in the last TextView

注意最后一個TextView中的不透明度

For more info on XML attributes for Android TextView, visit the Google docs attached at the end of this page or JournalDev Android TextView tutorial.

android kotlin, 有關Android TextView的XML屬性的詳細信息,請訪問此頁末尾隨附的Google文檔或JournalDev Android TextView教程。

In the following section, we’ll create TextView programmatically using Kotlin and set Kotlin functions, properties, and use lambda functions over the TextView.

在以下部分中,我們將使用Kotlin以編程方式創建TextView,并設置Kotlin函數,屬性,并在TextView上使用lambda函數。

使用Kotlin創建Android TextView (Creating Android TextView using Kotlin)

We can get the TextView in our MainActivity.kt Kotlin class using findViewById.

我們可以使用findViewById在MainActivity.kt Kotlin類中獲取TextView。

kotlin應用、The findViewById is used to get a view from the XML in the Activity class using the id specified. It works like a dictionary – key/value pair.

findViewById用于使用指定的ID從Activity類中的XML獲取視圖。 它像字典一樣工作-鍵/值對。

package net.androidly.androidtextviewkotlinimport android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextViewclass MainActivity : AppCompatActivity() {val TAG = "MainActivity"override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)var textView = findViewById<textview>(R.id.textView)//text property is equivalent to getText() or setText() in Java.Log.d(TAG,"TextView text is ${textView.text}") //Logs TextView text is Android TextView Color//setting the text.textView.text = "Text changed"//Setting the text from the strings.xml file.textView.text = resources.getString(R.string.app_name)}
}

Code Explanation:

代碼說明

  • MainActivity Kotlin class extends AppCompatActivity.

    MainActivity Kotlin類擴展了AppCompatActivity。
  • We’ve created the textView property by using findViewById. Though from Android API > 24 you can ignore specifying the type explicitly.

    我們使用findViewById創建了textView屬性 。 雖然從Android API> 24開始,您可以忽略顯式指定類型。
  • The text property is used as getter/setter on the TextView. It returns a CharSequence.

    text屬性用作TextView上的getter / setter方法。 它返回一個CharSequence 。
  • ${textView.text} implcitily converts the CharSequence to a String.

    ${textView.text} textView.text ${textView.text}隱式地將CharSequence轉換為String。
  • The text property in Kotlin is equivalent to getText() and setText(String) in Java.

    Kotlin中的text屬性等效于Java中的getText()setText(String)
  • To set the string from the strings.xml file, we call resources.getString(R.string.). The resources property is equivalent to getResources() from Java.

    要從strings.xml文件設置字符串,我們調用resources.getString(R.string. ) resources.getString(R.string. ) 。 resources屬性等效于Java中的getResources()

在TextView Kotlin代碼中處理空值 (Handling Null Values in TextView Kotlin Code)

Kotlin has a very safe way to deal with null values. Optional Types act as a wrapper over the current type. They need to be safely unwrapped to use non-null values, thus enabling null safety in our Kotlin code.

android反編譯教程、 Kotlin有一個非常安全的方法來處理空值。 可選類型充當當前類型的包裝。 需要安全地解開它們以使用非null值,從而在我們的Kotlin代碼中啟用null安全性。

Let’s look at how the above app behaves when the textView is null.

讓我們看一下當textView為null時上述應用程序的行為。

override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)var textView = findViewById<textview>(R.id.textView)textView.text = nullLog.d(TAG, "TextView text is ${textView.text}") // Logs TextView text istextView = nullLog.d(TAG, "TextView text is ${textView.text}") //compilation error. Add safe call.
}

So when the text is null, the compiler ignores it.

因此,當文本為null時 ,編譯器將忽略它。

Android版本10,When the textView is null, we need to add a safe call to unwrap the textView. This way Kotlin automatically gives us null safety.

textView為null時 ,我們需要添加一個安全調用以解開textView。 這樣Kotlin會自動為我們提供零安全。

What if the textView is null at runtime?

如果textView在運行時為null怎么辦?

override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)//we've set a random id available from the autocomplete just to set textView to null at runtime.var textView = findViewById<textview>(R.id.ALT) Log.d(TAG, "TextView text is ${textView.text}")}

It will throw error message as IllegalStateException. TextView cannot be null..

Android使用自帶文件。 它將引發錯誤消息為IllegalStateException. TextView cannot be null. IllegalStateException. TextView cannot be null.

So let’s set the TextView properties as Optional in the declaration.

因此,讓我們在聲明中將TextView屬性設置為Optional。

override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val otherTextView: TextView? = findViewById(R.id.textViewOpacity)otherTextView?.text = nullLog.d(TAG, "TextView displays ${otherTextView?.text ?: "NA"}")}

We’ve set otherTextView to the type TextView.

我們已經將otherTextView設置為TextView類型。

android Q,So calling anything over the TextView would require a safe call.

因此,通過TextView調用任何內容都需要安全的調用。

What if the text is null? What do we display instead?

如果文本為空怎么辦? 我們將顯示什么呢?

We use the elvis operator ?: from Kotlin for null safety.

Android基礎入門教程。 我們使用Kotlin的Elvis運算符?:來確保安全。

In the above code, NA gets displayed if otherTextView?.text is null.

在上面的代碼中,如果otherTextView?.text為null,則顯示NA。

The safe call can be replaced by a let lambda expression too.

安全調用也可以用let lambda表達式代替。

Kotlin Android擴展 (Kotlin Android Extensions)

android kotlin教程?Thanks to apply plugin: 'kotlin-android-extensions' in our build.gradle file, we can directly bind views from the layout in our Kotlin activity class.

感謝在build.gradle文件中apply plugin: 'kotlin-android-extensions' ,我們可以直接從Kotlin活動類中的布局中綁定視圖。

Add the following import statement in your MainActivity.kt class.

在MainActivity.kt類中添加以下導入語句。

import kotlinx.android.synthetic.main.activity_main.*

Now you can use the TextView properties directly without using findViewById.

現在,您可以直接使用TextView屬性,而無需使用findViewById。

Android TextView Kotlin onClick偵聽器 (Android TextView Kotlin onClick Listener)

package net.androidly.androidtextviewkotlinimport android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*class MainActivity : AppCompatActivity() {val TAG = "MainActivity"override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)//set textView to clickabletextView.isClickable = truetextView.setOnClickListener{ textView.text = resources.getString(R.string.app_name) }textViewClickMe.setOnClickListener { textViewClickMe.setTextColor(Color.WHITE) }textViewEllipsize.ellipsize = TextUtils.TruncateAt.MARQUEEtextViewEllipsize.setHorizontallyScrolling(true)textViewEllipsize.marqueeRepeatLimit = -1textViewEllipsize.isSelected = trueval mipMapDrawable = ContextCompat.getDrawable(this, R.mipmap.ic_launcher)textViewOpacity.setCompoundDrawablesWithIntrinsicBounds(mipMapDrawable,null,mipMapDrawable,null)}
}

In the above code, for the setOnClickListener we use lambda expressions from Kotlin. It makes the code shorter and easier to read than Java.

在上面的代碼中,對于setOnClickListener我們使用來自Kotlin的lambda表達式。 與Java相比,它使代碼更短,更易于閱讀。

To make the textViewEllipsize slide, set it to MARQUEE. To make it loop continuously, we’ve set marqueeRepeatLimit to -1.

要制作textViewEllipsize幻燈片,請將其設置為MARQUEE。 為了使其連續循環,我們將marqueeRepeatLimit設置為-1。

The mipMapDrawable is of the type Drawable and setCompoundDrawablesWithIntrinsicBounds() is the equivalent of android:drawablePadding.

mipMapDrawable的類型為Drawable,而setCompoundDrawablesWithIntrinsicBounds()等效于android:drawablePadding

The app output is shown in the following GIF.

應用程序的輸出顯示在以下GIF中。

Android TextView擴展功能 (Android TextView extension functions)

We can create Kotlin extension functions on a TextView to add our custom functions and properties.

我們可以在TextView上創建Kotlin擴展功能,以添加自定義功能和屬性。

The below extension function creates a consistent property for currentTextColor property and setTextColor() function.

下面的擴展函數為currentTextColor屬性和setTextColor()函數創建一致的屬性。

Add the following code outside the class.

在類外添加以下代碼。

var TextView.textColor: Int
get() = currentTextColor
set(v) = setTextColor(v)

We can then set the color on our TextView using the textColor property.

然后,我們可以使用textColor屬性在TextView上設置顏色。

textViewOpacity.textColor = ContextCompat.getColor(this, R.color.colorPrimaryDark)

Android TextView“帶有”表達式 (Android TextView “with” expression)

Instead of using redundant lines where we set the attributes on the same TextView property like this:

代替使用多余的行,我們在同一個TextView屬性上像下面這樣設置屬性:

textViewEllipsize.ellipsize = TextUtils.TruncateAt.MARQUEE
textViewEllipsize.setHorizontallyScrolling(true)
textViewEllipsize.marqueeRepeatLimit = -1
textViewEllipsize.isSelected = true
textViewEllipsize.setOnClickListener { println("So many calls to the same TextView") }

We can make it better using the with expression.

我們可以使用with表達式使它更好。

with(textViewEllipsize){ellipsize = TextUtils.TruncateAt.MARQUEEsetHorizontallyScrolling(true)marqueeRepeatLimit = -1isSelected = truesetOnClickListener { println("WOW. AWESOME.") }}

在Kotlin中以編程方式創建TextView (Creating a TextView Programmatically in Kotlin)

Below, we’ve created two TextViews programmatically. We’ve set a custom font from the assets folder and set underline on one of the TextViews. Also, we’ve set the string in the form of HTML.

下面,我們以編程方式創建了兩個TextView。 我們從資產文件夾中設置了自定義字體,并在其中一個TextViews上設置了下劃線。 另外,我們將字符串設置為HTML形式。

The assets directory is created under src | main folder and is used to hold the TTF files for the custom fonts.

資產目錄在src |下創建 main文件夾,用于保存自定義字體的TTF文件。

package net.androidly.androidtextviewkotlinimport android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.Html
import android.text.TextUtils
import android.view.Gravity
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*class MainActivity : AppCompatActivity() {val TAG = "MainActivity"lateinit var programmaticTextView : TextViewvar optionalTextView : TextView? = nulloverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)programmaticTextView = TextView(this)with(programmaticTextView){text = "I'm Created Programmatically. Kotlin makes life simple"textSize = 20ftextColor = Color.parseColor("#1F2135")typeface = Typeface.DEFAULT_BOLDisClickable = truesetOnClickListener { println("I contain the string: $text") }}linearLayout.addView(programmaticTextView)optionalTextView = TextView(this)optionalTextView.let { with(optionalTextView!!){text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {"${Html.fromHtml("<h4>this is underlined text</h4>Body goes here",Html.FROM_HTML_MODE_LEGACY)}"} else {@Suppress("DEPRECATION")"${Html.fromHtml("this is <u>underlined</u> text")}"}typeface = Typeface.createFromAsset(assets, "Pacifico.ttf")textSize = 20fgravity = Gravity.CENTERpaintFlags = Paint.UNDERLINE_TEXT_FLAG} }linearLayout.addView(optionalTextView)}
}var TextView.textColor: Intget() = currentTextColorset(v) = setTextColor(v)

Kotlin properties are required to be initialized there itself. If it’s not possible, we can set a lateinit modifier to the property.

Kotlin屬性需要在此處本身進行初始化。 如果不可能,我們可以為屬性設置lateinit修飾符。

By default, when the textView is created programmatically, its width is match_parent and height is wrap_content.

默認情況下,以編程方式創建match_parent ,其寬度為match_parent ,高度為wrap_content

The paintFlags is used to add an underline to the string.

paintFlags用于在字符串上添加下劃線。

The output with the above TextViews added into the layout programmatically is shown in the following image.

下圖顯示了將上述TextViews以編程方式添加到布局中的輸出。

使用可擴展字符串 (Using Spannable Strings)

Spannable Strings are useful when we have to set different styles on different substrings of the TextView.

當我們必須在TextView的不同子字符串上設置不同的樣式時,可擴展字符串很有用。

val string = "this is normal, this is underlined"
val firstWord = string.substringBefore(",")
val secondWord = string.substringAfterLast(",")
val redColor = ForegroundColorSpan(ContextCompat.getColor(this,android.R.color.holo_red_dark))val ssb = SpannableStringBuilder(firstWord)ssb.setSpan(redColor, // the span to add0, // the start of the span (inclusive)ssb.length, // the end of the span (exclusive)Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
ssb.append(" ")val underlineSpan = UnderlineSpan()ssb.append(secondWord)
ssb.setSpan(underlineSpan,ssb.length - secondWord.length,ssb.length,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)optionalTextView = TextView(this)optionalTextView.let { with(optionalTextView!!)
{text = ssbtypeface = Typeface.createFromAsset(assets, "Pacifico.ttf")textSize = 20fgravity = Gravity.CENTER} }linearLayout.addView(optionalTextView)

Output:

輸出:

This brings an end to the comprehensive tutorial on Android TextViews using Kotlin programming.

這結束了使用Kotlin編程的有關Android TextViews的綜合教程。

AndroidTextViewKotlinAndroidTextViewKotlin

翻譯自: https://www.journaldev.com/64/android-textview-using-kotlin

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/183113.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息