如何基於 Android EditText 焦點使用 Kotlin 顯示軟鍵盤?
本例演示瞭如何基於 Android EditText 焦點使用 Kotlin 顯示一個軟鍵盤。
步驟 1 − 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新專案並填寫所有必需的資訊來建立新專案。
步驟 2 − 將以下程式碼新增到 res/layout/activity_main.xml 中。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#f2f6f4" android:padding="10dp" tools:context=".MainActivity"> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:background="#008080" android:padding="5dp" android:text="TutorialsPoint" android:textColor="#fff" android:textSize="24sp" android:textStyle="bold" /> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/text2" android:layout_centerInParent="true" android:layout_marginTop="50dp" /> </RelativeLayout>
步驟 3 − 將以下程式碼新增到 src/MainActivity.kt 中
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var editText: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
editText = findViewById(R.id.editText)
showSoftKeyboard(editText)
}
private fun showSoftKeyboard(view: View) {
if (view.requestFocus()) {
val inputMethodManager: InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
}步驟 4 − 將以下程式碼新增到 androidManifest.xml 中
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
讓我們嘗試執行你的應用程式。我假設你已經將你的 Android 手機連線到電腦。從安卓工作室執行應用,開啟你專案中的一個活動檔案並點選執行
工具欄中的圖示。選擇你的移動裝置作為選項,然後檢查你的移動裝置,它會顯示你的預設螢幕。

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP