如何在 Android 應用中使用 AutoCompleteTextView?
本例演示瞭如何使用 Android 應用中的 AutoCompleteTextView。
步驟 1 − 在 Android Studio 中建立一個新專案,依次轉到檔案 ⇒ 新專案並填寫所有必填項以建立一個新專案。
步驟 2 − 將以下程式碼新增到 res/layout/activity_main.java 中
<? 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" android :orientation= "vertical" tools :context= ".MainActivity" > <android.support.v7.widget.AppCompatAutoCompleteTextView android :id= "@+id/autoTextView" android :layout_width= "match_parent" android :layout_height= "wrap_content" android :hint= "Enter fruit name" android :textColor= "#000000" android :textColorHint= "#000000" /> </LinearLayout>
步驟 3 − 將以下程式碼新增到 src/MainActivity.java 中
package app.tutorialspoint.com.sample ; import android.os.Bundle ; import android.support.v7.app.AppCompatActivity ; import android.support.v7.widget.AppCompatAutoCompleteTextView ; import android.widget.ArrayAdapter ; public class MainActivity extends AppCompatActivity { private String[] fruits = { "Apple" , "Banana" , "Cherry" , "Date" , "Grape" , "Kiwi" , "Mango" , "Pear" } ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; AppCompatAutoCompleteTextView autoTextView = findViewById(R.id. autoTextView ) ; ArrayAdapter<String> adapter = new ArrayAdapter<>( this, android.R.layout. select_dialog_item , fruits ) ; autoTextView.setThreshold( 1 ) ; //will start working from first character autoTextView.setAdapter(adapter) ; } }
步驟 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" > <uses-permission android :name= "android.permission.VIBRATE" /> <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>
讓我們嘗試執行您的應用程式。我認為您已將安卓手機與您的電腦連線。若要從安卓工作室執行應用程式,開啟一個專案的活動檔案,並點選工具欄中的執行 圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 –
廣告