如何在 Android 中限制 EditText 文字長度?


本示例演示如何在 Android 中限制 EditText 文字長度。

步驟 1 − 在 Android Studio 中新建一個專案,轉到檔案 ⇒ 新專案並填寫所有必填項來建立新專案。

步驟 2 − 將以下程式碼新增到 res/layout/activity_main.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 :layout_margin= "16dp"
   tools :context= ".MainActivity" >
   <EditText
      android :layout_width= "match_parent"
      android :layout_height= "wrap_content"
      android :hint= "Enter something..."
      android :maxLength= "10" />
</LinearLayout>

步驟 3 − 將以下程式碼新增到 src/MainActivity.java 中

package app.tutorialspoint.com.sample ;
import android.support.v7.app.AppCompatActivity ;
import android.os.Bundle ;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      setContentView(R.layout. activity_main ) ;
   }
}

步驟 4 − 將以下程式碼新增到 androidManifest.xml 中

<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
   package= "app.tutorialspoint.com.sample" >
   <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 移動裝置與你的計算機連線起來了。要透過 Android Studio 執行該應用,開啟專案的任意一個活動檔案並單擊工具欄上的 Run  圖示。將你的移動裝置選擇為一個選項,然後檢視移動裝置,它會顯示你的預設螢幕


更新於:2019-07-30

5K+ 瀏覽

開啟你的 事業

完成課程,獲得認證

開始
廣告
© . All rights reserved.