Android AutoCompleteTextView 示例
Android AutoCompleteTextView 根据保留的单词进行字词补全,因此无需编写单词的所有字符。
Android AutoCompleteTextView是可编辑的文本字段,它在下拉菜单中显示建议列表,用户可以仅选择一个建议或值。
Android AutoCompleteTextView是EditText类的子类。而MultiAutoCompleteTextView是AutoCompleteTextView类的子类。
Android AutoCompleteTextView示例
在此示例中,我们将编程语言显示在自动完成文本视图中。所有的编程语言都存储在字符串数组中。我们使用 ArrayAdapter 类来显示数组内容。
让我们看看Android中autocompletetextview的简单示例。
activity_main.xml
从面板中拖动AutoCompleteTextView和TextView,现在activity_main.xml文件将会是这样的:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.autocompletetextview.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What is your favourite programming language?"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.032" />
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="92dp"
android:layout_marginTop="144dp"
android:text=""
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Activity类
让我们来编写AutoCompleteTextView的代码。
package example.javatpoint.com.autocompletetextview;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends AppCompatActivity {
String[] language ={"C","C++","Java",".NET","iPhone","Android","ASP.NET","PHP"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the instance of ArrayAdapter containing list of language names
ArrayAdapter adapter = new ArrayAdapter
(this,android.R.layout.select_dialog_item,language);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
actv.setTextColor(Color.RED);
}
}