activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="com.example.my_autocompletetextview.MainActivity">
<AutoCompleteTextView
android:id="@+id/autocomplete"
android:completionThreshold="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:text="Hello World!"-->
<!--app:layout_constraintBottom_toBottomOf="parent"-->
<!--app:layout_constraintLeft_toLeftOf="parent"-->
<!--app:layout_constraintRight_toRightOf="parent"-->
<!--app:layout_constraintTop_toTopOf="parent" />-->
</LinearLayout>
item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:src="@mipmap/ic_launcher"
android:layout_width="30dp"
android:layout_height="30dp" />
<TextView
android:id="@+id/text"
android:textSize="20sp"
android:text="hah"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
package com.example.my_autocompletetextview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1.准备数据源
final String string[] = {"北京","上海","广州","1235","hello"};
//2.准备适配器
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
MainActivity.this, //
R.layout.item, //显示的布局
R.id.text, //显示的字符串
string); //数据源
//3.让控件和适配器进行关联
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autocomplete);
autoCompleteTextView.setAdapter(adapter);
//当点击了某一列响应
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,string[i],Toast.LENGTH_LONG).show();
}
});
}
}
效果:(输出代码中具有的字符串的时候,会自动显示出来!)
image.png
网友评论